外键取决于第二个外键

问题描述

| 我的问题很简单,但是找不到任何解决方案。可以说我有以下内容:
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中指定的类别,建立从餐桌食物到餐桌水果+蔬菜的外键约束。这可能吗?     

解决方法

如果您的问题确实如此简单,则只需使用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或带有FOREIGN KEY CONSTRAINT的外部表。     ,外键只能引用主键或唯一键。您的
food.food_id
都不是。那是技术方面。从架构设计的角度来看,我不确定是否可能有太多的表格供您使用。     ,我将您的模型更改为此:
Table food:
id (key);
name;
category_id;

Table category:
category_id (key);
category_names [fruits,vegetables]
我看不到为什么您需要水果和蔬菜的桌子,除非那些桌子与其他桌子有不同的关系。 您还可以阅读有关在数据库中对子类建模的页面 祝好运!     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...