我有一组以下表格:
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约束?
答案 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 ;