外键依赖于第二个外键

发布于 2024-11-09 07:57:45 字数 352 浏览 0 评论 0原文

我的问题很简单,但我找不到任何解决方案。可以说我有以下内容:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

铜锣湾横着走 2024-11-16 07:57:45

如果您的问题确实如此简单,那么只需使用 VIEWS:

CREATE TABLE food (
  id SERIAL,
  name TEXT NOT NULL,
  category TEXT NOT NULL,
  PRIMARY KEY(id),
  CHECK(category = 'fruit' OR category = 'veggie')
);
CREATE UNIQUE INDEX food_name_udx ON food(name);

CREATE VIEW fruit AS
  SELECT id, name FROM food WHERE category = 'fruit';

CREATE VIEW veggie AS
  SELECT id, name FROM food WHERE category = 'veggie';

如果类别增长超过 5-10 个条目,则使用 DOMAINS 或带有外键约束的外部表。

If your problem is really that simple, then just use VIEWS:

CREATE TABLE food (
  id SERIAL,
  name TEXT NOT NULL,
  category TEXT NOT NULL,
  PRIMARY KEY(id),
  CHECK(category = 'fruit' OR category = 'veggie')
);
CREATE UNIQUE INDEX food_name_udx ON food(name);

CREATE VIEW fruit AS
  SELECT id, name FROM food WHERE category = 'fruit';

CREATE VIEW veggie AS
  SELECT id, name FROM food WHERE category = 'veggie';

Use DOMAINS or an external table with a FOREIGN KEY CONSTRAINT if category grows beyond 5-10 entries.

灯下孤影 2024-11-16 07:57:45

外键只能引用主键或唯一键。您的 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.

情泪▽动烟 2024-11-16 07:57:45

我会将您的模型更改为:

Table food:
id (key);
name;
category_id;

Table category:
category_id (key);
category_names [fruits, vegetables]

我不明白为什么您需要一张水果和蔬菜的桌子,除非这些桌子与其他桌子有不同的关系。

您还可以阅读有关 在数据库中建模子类

祝你好运!

I'd change your model to this:

Table food:
id (key);
name;
category_id;

Table category:
category_id (key);
category_names [fruits, vegetables]

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文