database - N表有1个:1 relationship with a common table?如何保证唯一性

标签 database database-design constraints

假设我有一个具有以下模型的场景:一个代表任何动物的 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/

相关文章:

java - 将数据库表转换为 JTree

ios - 自动布局视觉格式语言

mysql - 4维数据库网格

swift - 如何在 Swift 中设置 NSLayoutConstraint?

java - 光规划器 :Error when displaying constraints scores

mysql - 从 mysql 表中的同一列获取计数?

sql - 基础R : Aggregate and sum by two columns

database - 在 DynamoDB 中设计 "social-feed"

database - 有经验的数据库架构师的话题

mysql - 关于构建评论系统的建议