1

我有以下一组表格:

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 约束强制执行一个卖家只能拥有一张给定编号的发票的约束。

buyers我想创建一个新表,主要是和之间的多对多关系sellers

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 约束?

4

1 回答 1

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 ;
于 2013-06-06T18:53:00.890 回答