Database design 如何使用不同类型的产品设计数据库
我有一家商店,目前出售三种不同类型的商品:视频游戏、控制台和电缆。我正试图找出如何设计一个表,供这三个项目使用 我认为每种类型都有以下特性:Database design 如何使用不同类型的产品设计数据库,database-design,relational-database,Database Design,Relational Database,我有一家商店,目前出售三种不同类型的商品:视频游戏、控制台和电缆。我正试图找出如何设计一个表,供这三个项目使用 我认为每种类型都有以下特性: Video Game - name - console Console - name Cable - name 我想出了这个设计: Product - Type - Name - Console 因此,它可以转化为: id | type | name | console ---+---------+-------------
Video Game
- name
- console
Console
- name
Cable
- name
我想出了这个设计:
Product
- Type
- Name
- Console
因此,它可以转化为:
id | type | name | console
---+---------+---------------+---------
1 | game | Goldeneye | N64
2 | console | SNES | null
3 | cable | HDMI | null
4 | game | Smash Bros | Wii
但是对于console
和cable
类型化产品,console列始终为空。此外,我认为如果我决定销售另一种需要另一个专栏的产品(即电视显示器和包括屏幕尺寸),这种设计可能会有很大的限制
有没有更好的方法来设计我的桌子
我环顾四周,发现这个解决方案似乎很理想:。我将创建一个引用属性表的通用产品表。在这种情况下,DB将无法强制使用Attirbutes(即,所有游戏都必须具有console属性)。您可以轻松地拥有两张桌子
1. Product
2. Attributes
表结构可以是这样的
Product
id | type | name
---+---------+---------------
1 | game | Goldeneye
2 | console | SNES
3 | cable | HDMI
4 | game | Smash Bros
5 | TV | LG
Attributes
id | product_id | type | value
---+------------+-------------+---------
1 | 1 | console | N64
2 | 4 | console | Wii
3 | 5 | screen size | 50"
让我知道这是否解决了您的问题您可以轻松拥有两张表
1. Product
2. Attributes
表结构可以是这样的
Product
id | type | name
---+---------+---------------
1 | game | Goldeneye
2 | console | SNES
3 | cable | HDMI
4 | game | Smash Bros
5 | TV | LG
Attributes
id | product_id | type | value
---+------------+-------------+---------
1 | 1 | console | N64
2 | 4 | console | Wii
3 | 5 | screen size | 50"
让我知道这是否解决了您的问题您需要的是与Products表的多态关联 有一个通用产品表,该表将具有项目类型和项目id:
id | item_type | item_id
1 | VideoGame | 1
2 | Console | 1
3 | Cable | 1
4 | VideoGame | 2
电子游戏桌:
id | name | price
1 | Goldeneye | 59
2 | FIFA19 | 88
控制台表:
id | name | price
1 | SNES | 200
2 | WhateverName | 300
电缆表
id | name | price
1 | HDMI | 20
2 | CAT6 | 30
现在每个产品都可以在Products表中找到,您可以在item\u id
和item\u type
的帮助下获得准确的产品
在这里,id=4的产品实际上是名为FIFA19
的视频游戏,它的所有相关细节都可以从控制台
表中找到,就像它的价格是88一样
所以基本上,您只需根据商品的类型和id查询商品表,就可以访问该记录
希望这有帮助:)您需要的是与Products表的多态关联 有一个通用产品表,该表将具有项目类型和项目id:
id | item_type | item_id
1 | VideoGame | 1
2 | Console | 1
3 | Cable | 1
4 | VideoGame | 2
电子游戏桌:
id | name | price
1 | Goldeneye | 59
2 | FIFA19 | 88
控制台表:
id | name | price
1 | SNES | 200
2 | WhateverName | 300
电缆表
id | name | price
1 | HDMI | 20
2 | CAT6 | 30
现在每个产品都可以在Products表中找到,您可以在item\u id
和item\u type
的帮助下获得准确的产品
在这里,id=4的产品实际上是名为FIFA19
的视频游戏,它的所有相关细节都可以从控制台
表中找到,就像它的价格是88一样
所以基本上,您只需根据商品的类型和id查询商品表,就可以访问该记录
希望这有帮助:)