【发布时间】:2019-02-06 02:55:33
【问题描述】:
我希望使用表 A 中的两列作为两个表之一的外键:表 B 或表 C。使用列 table_a.item_id 和 table_a.item_type_id,我想强制任何新行具有表 B 或表 C 中匹配的 item_id 和 item_type_id。
示例:
Table A: Inventory
+---------+--------------+-------+
| item_id | item_type_id | count |
+---------+--------------+-------+
| 2 | 1 | 32 |
| 3 | 1 | 24 |
| 1 | 2 | 10 |
+---------+--------------+-------+
Table B: Recipes
+----+--------------+-------------------+-------------+----------------------+
| id | item_type_id | name | consistency | gram_to_fluid_ounces |
+----+--------------+-------------------+-------------+----------------------+
| 1 | 1 | Delicious Juice | thin | .0048472 |
| 2 | 1 | Ok Tasting Juice | thin | .0057263 |
| 3 | 1 | Protein Smoothie | heavy | .0049847 |
+----+--------------+-------------------+-------------+----------------------+
Table C: Products
+----+--------------+----------+--------+----------+----------+
| id | item_type_id | name | price | in_stock | is_taxed |
+----+--------------+----------+--------+----------+----------+
| 1 | 2 | Purse | $200 | TRUE | TRUE |
| 2 | 2 | Notebook | $14.99 | TRUE | TRUE |
| 3 | 2 | Computer | $1,099 | FALSE | TRUE |
+----+--------------+----------+--------+----------+----------+
Other Table: Item_Types
+----+-----------+
| id | type_name |
+----+-----------+
| 1 | recipes |
| 2 | products |
+----+-----------+
我希望能够有一个库存表,员工可以在其中输入库存计数,无论项目是配方还是产品。我不想拥有 product_inventory 和 recipe_inventory 表,因为无论项目类型如何,我都需要对所有库存项目执行许多操作。
一种解决方案是像这样创建一个参考表:
Table CD: Items
+---------+--------------+------------+-----------+
| item_id | item_type_id | product_id | recipe_id |
+---------+--------------+------------+-----------+
| 2 | 1 | NULL | 2 |
| 3 | 1 | NULL | 3 |
| 1 | 2 | 1 | NULL |
+---------+--------------+------------+-----------+
这看起来很麻烦,而且我现在需要从这个新表中添加/删除产品/食谱,只要它们从各自的表中添加/删除。 (有没有自动的方法来实现这一点?)
CREATE TABLE [dbo].[inventory] (
[id] [bigint] IDENTITY(1,1) NOT NULL,
[item_id] [smallint] NOT NULL,
[item_type_id] [tinyint] NOT NULL,
[count] [float] NOT NULL,
CONSTRAINT [PK_inventory_id] PRIMARY KEY CLUSTERED ([id] ASC)
) ON [PRIMARY]
我真正想做的是这样的事情......
ALTER TABLE [inventory]
ADD CONSTRAINT [FK_inventory_sources] FOREIGN KEY ([item_id],[item_type_id])
REFERENCES {[products] ([id],[item_type_id]) OR [recipes] ([id],[item_type_id])}
也许没有我所描述的解决方案,所以如果您有任何想法可以让我保持相同/相似的架构,我绝对愿意听取他们的意见! 谢谢:)
【问题讨论】:
-
请在关系型数据库和父/子表中搜索模型继承。
-
你真的可以三思而后行他的设计。看起来你正在做一个不必要的非规范化,只有@KjetilNordin 的回答才是重点。作为建议,您可以创建一个项目表,其中包含类型和名称列以及威胁配方和产品作为指向项目的详细信息
标签: sql sql-server azure-sql-database