假设我有一个具有以下模型的场景:一个代表任何动物的 Animal
表,一个 Dog
表和一个 Bird
表,每个都与 Animal
表具有 1:1 的关系。
动物
INTEGER id (PK)
STRING name
鸟
INTEGER id (PK FK referencing `Animal.id`)
狗
INTEGER id (PK FK referencing `Animal.id`)
(为了清楚起见,我只给出了 key )
我如何保证 Animal
表中的给定行在 Dog
或 中只有一个引用行>鸟
表?模型本身允许它...
动物不能同时是狗
和鸟
(不是神话,但事实并非如此:P )
如果这可以通过玩模型而不使用触发器来完成,那就更好了......
任何提示将不胜感激:)
最佳答案
这可能是@Pranay 的意思,但答案不完整。为所有表添加一个列 TYPE,然后像这样对其进行约束:
create table Animal (id integer,
type string,
name string,
primary key (id),
unique (id, type)
);
create table Bird (id integer,
type string default 'BIRD' check (type='BIRD'),
primary key (id),
foreign key (id, type) references Animal (id, type)
);
create table Dog (id integer,
type string default 'DOG' check (type='DOG'),
primary key (id),
foreign key (id, type) references Animal (id, type)
);
参见 David Portas's blog对此有一个很好的解释。
关于database - N表有1个:1 relationship with a common table?如何保证唯一性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7025416/