PostgreSQL:2个表之间的完整性约束

问题描述 投票:1回答:2

我正在使用PostgreSQL并具有以下两个表:

create table anomaly (
    id          bigint          not null unique,
    description text            not null,
    zone1       varchar(100)    not null,
    language1   varchar(100)    not null,
    is_translation_anomaly  boolean not null,
    primary key(id)
);

create table translation_anomaly (
    id          bigint          not null unique,
    zone2       varchar(100)    not null,
    language2   varchar(100)    not null,
    primary key(id),
    foreign key(id) references anomaly(id)
);

平移异常(translation_anomaly)是anomaly的规范。我想实现以下两个完整性约束,而不使用触发器或存储过程:

  • zone1必须不同于zone2
  • 语言1必须与语言2不同

我看过thisthis问题,但都无法从我的案例中得到答案。我是SQL的新手,所以如果我错过了我应该选择的答案,我深表歉意。

我正在使用PostgreSQL 9.4.10。

谢谢您!

database-design constraints postgresql-9.4
2个回答
0
投票

[阅读了大量文档并向我的老师寻求帮助之后,我得出的结论是:[[不可能在不使用触发器或存储过程的情况下实现上述完整性约束是可能的。如果确实需要采取这些措施,那么PostgreSQL的官方文档非常好:)


0
投票
我怀疑您的表设计未正确归一化。我不知道您的业务问题的语义,所以我只能猜测。

如果子表代表本地化版本中的翻译,则包括原始值在内的所有值都应出现在子表中。

例如,如果您打算将英语措辞存储在父表中,而子表保留法语和阿拉伯语,则不要这样做。子表中应同时显示所有三个(英语,法语,阿拉伯语)。

顺便说一下,每个表都需要有自己的唯一标识符。因此,您的子表需要两个字段,一个是其自己的标识符(主键),另一列是其父代的标识符(外键)。

create table anomaly ( id bigint not null unique, description text not null, is_translation_anomaly boolean not null, primary key(id) ); create table translation_anomaly ( id bigint not null unique, anomaly_id bigint not null, zone varchar(100) not null, language varchar(100) not null, primary key(id), foreign key( anomaly_id ) references anomaly(id) );

为列anomaly_idzone的组合定义唯一索引以强制执行第一条规则。同上languageanomaly_id来强制执行第二条规则。 
© www.soinside.com 2019 - 2024. All rights reserved.