【发布时间】:2021-04-13 15:49:17
【问题描述】:
有一个名为consists_of 的表与产品类别层次结构相关。
CREATE TABLE consists_of(
super_name VARCHAR(80),
sub_name VARCHAR(80),
UNIQUE(super_name, sub_name),
PRIMARY KEY(sub_name),
FOREIGN KEY(sub_name) REFERENCES category(name),
FOREIGN KEY(super_name) REFERENCES category(name),
CHECK (sub_name <> super_name)
);
如何防止循环关系,例如:
INSERT INTO consists_of values ('Cheese', 'Cheddar')
INSERT INTO consists_of values ('Cheddar', 'Cheese')
【问题讨论】:
-
就性能而言,触发器可能有点昂贵,但假设有时 sub_name 和 super_name 相同是可以的,很难看到有任何方法可以通过约束来防止这种情况,所以我会说触发器是最可靠的方法。 postgresql.org/docs/13/sql-createtrigger.html
-
我不会使用
VARCHAR(80)作为键。这将导致庞大的索引。
标签: database postgresql unique