我必须按下面所示的方式创建一个表。我们能用这种方式创造吗?(如果是)
表名:示例
product_id| product_name| category |
1 | Sample1 | 1|2|3 |
2 | sample2 | 4|5|6 |
其中包含多个值的类别字段。
&如何搜索类别4取决于表的哪一行。
最佳答案
不能创建嵌套表。你脑子里想的不是这样设计桌子的好主意。您应该有两个表(如果是类别,则正好有三个表包含说明)。一个用于product
,第二个表包含每个产品的类别。示例设计如下所示,
CREATE TABLE Product
(
ProductID INT PRIMARY KEY,
ProductName VARCHAR(50) UNIQUE
);
CREATE TABLE Category
(
CategoryID INT PRIMARY KEY,
CategoryName VARCHAR(50) UNIQUE
);
CREATE TABLE Product_Category
(
RecordD INT AUTO_INCREMENT PRIMARY KEY,
CategoryID INT,
ProductID INT,
CONSTRAINT tb_uq UNIQUE(CategoryID, ProductID)
);
并填充样本记录
INSERT Category VALUES (1, 'Fruit');
INSERT Category VALUES (2, 'Vegetable');
INSERT Product VALUES (1, 'Apple');
INSERT Product VALUES (2, 'Banana');
INSERT Product VALUES (3, 'Cabbage');
INSERT Product VALUES (4, 'Squash');
INSERT Product VALUES (5, 'Tomato');
INSERT Product_Category (CategoryID, ProductID) VALUES (1,1);
INSERT Product_Category (CategoryID, ProductID) VALUES (1,2);
INSERT Product_Category (CategoryID, ProductID) VALUES (2,3);
INSERT Product_Category (CategoryID, ProductID) VALUES (2,4);
INSERT Product_Category (CategoryID, ProductID) VALUES (1,5);
INSERT Product_Category (CategoryID, ProductID) VALUES (2,5);
SQLFiddle Demo (with records included)
示例查询
-- NORMAL QUERY
SELECT a.ProductName, c.CategoryName
FROM Product a
INNER JOIN Product_category b
ON a.ProductID = b.ProductID
INNER JOIN Category c
ON b.CategoryID = c.CategoryID
ORDER BY ProductName;
-- If you want catgoryName to be comma separated
SELECT a.ProductName, GROUP_CONCAT(c.CategoryName) CategoryList
FROM Product a
INNER JOIN Product_category b
ON a.ProductID = b.ProductID
INNER JOIN Category c
ON b.CategoryID = c.CategoryID
GROUP BY ProductName
ORDER BY ProductName;