如何构建表来建模互斥 1:n 关系?
在下面的表结构中:
Fruits
(
fruit_id,
fruitName
)
Vegetables
(
vegetable_id,
vegetableName
)
favoriteFoods
(
food_id,
foodName,
type_id (References either a fruit or a vegetable)
)
我意识到我可以放弃在 favoriteFoods 表上使用外键约束,然后只需向 favoriteFoods 表添加一个类型字段来区分水果和蔬菜。 但是,如何构建表以便能够实际创建必要的外键约束呢?
In the following table structure:
Fruits
(
fruit_id,
fruitName
)
Vegetables
(
vegetable_id,
vegetableName
)
favoriteFoods
(
food_id,
foodName,
type_id (References either a fruit or a vegetable)
)
I realize that I could forgo using a foreign key constraint on the favoriteFoods table and then simply add a type field to the favoriteFoods table to differentiate between fruits and vegetables. But how would you structure the tables so that you could actually create the necessary foreign key constraints?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我只会使用 2 张桌子。 与其有一个单独的水果和蔬菜表,不如有一个食物表。 然后对 fkfood_id 进行外键约束到 food_id。 然后,如果由于某种原因您必须添加肉,那么维护使用它的应用程序就会容易得多。
I would only use 2 tables instead. Instead of having a separate Fruits and Vegetables table, why not have a table of Foods. Then have a foreign key constraint on fkfood_id to food_id. Then if for some reason you ever have to add meat, it would be much easier to maintain the application that uses this.
这取决于您要如何处理数据。
如果由于某种原因标准化对您很重要,那么以下方法非常有效。
favoriteFoods 表不需要“知道”它是什么类型的食物(如果有的话)。 每种水果和每种蔬菜都与相应的喜爱的食物绑定。
如果你想从favoriteFoods中选择所有水果,只需加入fruits表和favoriteFoods表即可。 如果您喜欢的话,您甚至可以将西红柿既作为蔬菜又作为水果。
以上是基于连接成本低廉的假设。 在许多情况下,连接确实很便宜。 在改变设计之前检查一下以避免连接。
It depends on what you are going to do with the data.
If for some reason normalization is important to you, the following works quite well.
The favoriteFoods table doesn't need to "know" what type of food it is, if any. Each fruit and each vegetable is bound to the corresponding favorite food.
If you want to select all the fruits from favoriteFoods, just join the fruits table and the favoriteFoods table. You could even include a tomato as both a vegetable and a fruit, if that suits your fancy.
The above is predicated on the assumption that joins are cheap. In many situations, joins really are cheap. Check it out before you alter your design to avoid joins.