您永远不应该使用具有可变列数的任何类型的解决方案(即您的第一个解决方案)。不能保证一个产品最多有 7 个类别,也不能保证一个产品甚至会有一个类别。您最终将不得不ALTER
经常访问此表,并且没有指定多个列的简单方法来选择类别。
第二种解决方案要好得多——它的表Categories
在每一行都有一个标识符和类别名称。然后,您只需要另一个具有(产品标识符、类别标识符)的表,您可以将产品链接到任意数量的类别。
CREATE TABLE Categories (
catID int unsigned not null auto_increment primary key,
catName varchar(255),
unique key (catName)
);
CREATE TABLE ProductCategories (
pcID int unsigned not null auto_increment primary key,
proID int unsigned,
catID int unsigned,
unique key (proID, catID),
foreign key (proID) references Products (id),
foreign key (catID) references Categories (catID)
);