我正在创建一个在线商店来销售枪支和相关元素。我一直致力于完善数据库 (MySQL),因为它将成为网站的支柱。我的问题是,在保持规范化优先的同时,我无法全神贯注于应该如何布局数据库。该网站有许多产品,大多数产品信息相同,但许多产品有细微差别。
例如,弹药有四个类别,四个类别中的三个具有相同的信息,最后一个具有不同的信息。我会为三个相同的表格制作一张表格,为具有不同信息的表格制作一张单独的表格吗?或者我会创建表格并有一个列可以容纳一个数组或 JSON 字符串,其中包含该产品的差异吗?
请记住,许多产品都存在相同的问题。我不害怕工作,我只是想确保我走在正确的道路上。
让我简要介绍一下我的类别:
• Firearms
• handguns (unique characteristics)
• centerfire rifles (unique characteristics)
• rimfire rifles (same as above)
• Ammunition
• rifle ammo (unique characteristics)
• handgun ammo (same as above)
• rimfire ammo (same as above)
• shotgun ammo (unique characteristics)
• Shooting Accessories
• there are many products here with unique characteristics
• Optics
• there are many products here with unique characteristics
• MANY MORE ...
我很想创建一个名为 products 的表并将它们全部放在该表中,但由于存在所有细微差别,我确信这是不可能的。
*编辑*
这是我将拥有的属性差异的示例:
• Rifle Ammunition
• manufacturer
• model
• caliber
• bullet weight
• bullet type
• number of rounds
• price
• description
• sku
• rating
• Handgun Ammunition
• SAME AS ABOVE
• Rimfire Ammunition
• SAME AS ABOVE
• Shotgun Ammunition
• manufacturer
• model
• gauge
• shell length
• shot weight
• shot size
• velocity
• price
• description
• sku
• rating
步枪、手枪和 rimfire 将具有相同数量的属性 (10)。 Shotgun 将具有 (11) 个属性,并且还有更多类似此问题的实例。
感谢您的关注:)
最佳答案
我会做这样的事情:
产品表非常基本,您的主要产品详细信息:
create table products
(
id int,
name varchar(50)
);
insert into products values
(1, 'rifle ammunition'),
(2, 'handgun ammo');
我个人会使用类似于以下的模型:
产品表非常基本,您的主要产品详细信息:
create table product
(
part_number int, (PK)
name varchar(10),
price int
);
insert into product values
(1, 'product1', 50),
(2, 'product2', 95.99);
第二个属性表用于存储每个不同的属性。
create table attributes
(
id int,
attribute_name varchar(10),
attribute_value varchar(10)
);
insert into attributes values
(1, 'manufacturer', 'test'),
(2, 'model', 'blah'),
(3, 'bullet weight', '10'),
(4, 'bullet type', 'metal'),
(5, 'price', '50');
最后创建 product_attribute 表作为每个产品及其关联属性之间的 JOIN 表。该表将允许每个产品和属性有多个条目。因此,如果一个产品有 10 个属性,则将有 10 个条目。如果另一个有 2 个属性,则将有两个条目。
create table products_attributes
(
product_id int,
attribute_id int
);
insert into products_attributes values
(1, 1),
(1, 2),
(1, 3),
(1, 4),
(2, 1),
(2, 2),
(2, 3);
这使您可以灵活地处理具有多个属性或类别的许多产品。然后通过几个连接查询就很简单了(参见 SQL Fiddle With Demo ):
select *
from products p
left join products_attributes pa
on p.id = pa.product_id
left join attributes a
on pa.attribute_id = a.id;
查询结果为:
ID | NAME | PRODUCT_ID | ATTRIBUTE_ID | ATTRIBUTE_NAME | ATTRIBUTE_VALUE
-------------------------------------------------------------------------------
1 | rifle ammunition | 1 | 1 | manufacturer | test
1 | rifle ammunition | 1 | 2 | model | blah
1 | rifle ammunition | 1 | 3 | bullet weight | 10
1 | rifle ammunition | 1 | 4 | bullet type | metal
2 | handgun ammo | 2 | 1 | manufacturer | test
2 | handgun ammo | 2 | 2 | model | blah
2 | handgun ammo | 2 | 3 | bullet weight | 10
关于mysql - 如何布局我的数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12605104/