外键依赖于第二个外键
我的问题很简单,但我找不到任何解决方案。可以说我有以下内容:
Table food:
id (key);
category_id;
food_id
Table category:
category_id (key);
category_names [fruits, vegetables]
Table fruits
food_id (key);
fruit [apple, banana]
Table vegetables
food_id (key);
vegetable [bean, carrot]
我现在想要构建一个从餐桌食品到餐桌水果+蔬菜的外键约束,具体取决于category_id中指定的类别。这可能吗?
my problem is quite simple, but I cannot find any solution. Lets say i have the following:
Table food:
id (key);
category_id;
food_id
Table category:
category_id (key);
category_names [fruits, vegetables]
Table fruits
food_id (key);
fruit [apple, banana]
Table vegetables
food_id (key);
vegetable [bean, carrot]
I now want to build a foreign key constraint from table food to the tables fruits + vegetables, depending on the category, specified in category_id. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的问题确实如此简单,那么只需使用 VIEWS:
如果类别增长超过 5-10 个条目,则使用 DOMAINS 或带有外键约束的外部表。
If your problem is really that simple, then just use VIEWS:
Use DOMAINS or an external table with a FOREIGN KEY CONSTRAINT if category grows beyond 5-10 entries.
外键只能引用主键或唯一键。您的
food.food_id
两者都不是。这就是技术方面。从架构设计的角度来看,我不确定您是否有太多表无法满足您的目的。Foreign keys can only reference primary keys or unique keys. Your
food.food_id
is neither. That's the technical aspect. From the schema design point of view, I'm not sure if you may have too many tables for your purpose.我会将您的模型更改为:
我不明白为什么您需要一张水果和蔬菜的桌子,除非这些桌子与其他桌子有不同的关系。
您还可以阅读有关 在数据库中建模子类
祝你好运!
I'd change your model to this:
i can't see why you need a table for the fruits and vegetables, except if those tables have different relations to other tables..
you could also read this page about modeling subclasses in a database
Good Luck!