间接UNIQUE约束

时间:2013-06-06 18:44:16

标签: sql postgresql

我有一组以下表格:

CREATE TABLE sellers (
    id       integer PRIMARY KEY,
    ....
);

CREATE TABLE buyers (
    id       integer PRIMARY KEY,
    ....
);

CREATE TABLE invoices (
    id        integer PRIMARY KEY,
    number    varchar(40),
    buyer_id  integer REFERENCES buyers(id),
    seller_id integer REFERENCES sellers(id),
    UNIQUE(seller_id, number),
    ....
);

UNIQUE约束强制执行约束,即一个卖方只能拥有一个给定数量的发票。

我想创建一个新表,主要是buyerssellers之间的多对多关系:

CREATE TABLE suppliers (
    id        integer PRIMARY KEY,
    buyer_id  integer REFERENCES buyers(id),
    seller_id integer REFERENCES sellers(id),
    ....
);

作为规范化工作,我想更改invoices以引用suppliers,如下所示:

CREATE TABLE invoices (
    id        integer PRIMARY KEY,
    number    varchar(40),
    supplier_id  integer REFERENCES suppliers(id),
    ....
);

我的问题是:如何替换UNIQUE约束?

1 个答案:

答案 0 :(得分:4)

使用suppliers的复合主键:

CREATE TABLE suppliers (
    buyer_id  integer REFERENCES buyers(id),
    seller_id integer REFERENCES sellers(id),
    ...
    PRIMARY KEY (buyer_id, seller_id),
    ...
);

并保持invoices表的完整性,只将两个外键更改为一个:

CREATE TABLE invoices (
    id        integer PRIMARY KEY,
    number    varchar(40),
    buyer_id  integer,
    seller_id integer,
    UNIQUE (seller_id, number),
    FOREIGN KEY (buyer_id, seller_id)
      REFERENCES suppliers (buyer_id, seller_id),
    ....
);

如果您计划在suppliers表中有更多与seller - buyer关系相关的列,我想这个设计会很有用。否则,您可以拥有一个从invoices表中收集数据的视图:

CREATE VIEW suppliers AS
SELECT DISTINCT buyer_id, seller_id
FROM invoices ;