我有具有许多types
和许多grades
的表colors
。
我在grades
,type_id
和colors
中都放置了外键。
我有一个名为item
的第三个表,其中有一个grade
和color
。
我的问题是,如何确保从item
回到types
的数据的完整性。
例如:
Type:
0 sometype1
1 sometype2
grades:
0 somegrade 0 (points to sometype1)
color:
0 red 0 (points to sometype1)
item:
0 item1 0 0 (points to somegrade, red - which points to sometype1)
如何确保不会出现
color
和grade
正确但type
不正确的情况?另外,如果其中一个外键引用正确的类型而另一个不引用正确的类型,等等?
在我看来,必须有一种更好的建模方法,有人可以帮忙吗?
最佳答案
由于color
和grade
都引用types
,因此您可以让item
涉及所有三个id值,并使用它们自己的id和type_id引用两个表。由于外键约束将共享相同的type_id,因此将不可能引用不同类型的等级和颜色。
表格上的最少最小列为:
types: type_id
[no foreign key constraints]
grades: grade_id, type_id
[type_id references types.type_id]
colors: color_id, type_id
[type_id references types.type_id]
items: item_id, type_id, grade_id, color_id
[ (type_id, grade_id) should reference grades as one key
,(type_id, color_id) should reference colors as one key
, type_id would reference types but that should not need enforced with a constraint.
]
关于mysql - 关系数据库设计外键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30221383/