gpt4 book ai didi

sql - 为什么需要这个 UNIQUE 约束?

转载 作者:行者123 更新时间:2023-11-29 12:10:01 25 4
gpt4 key购买 nike

我正在尝试在 PostgreSQL 中设计架构,该架构将包含两个相互交叉引用的表。然而,如果不添加冗余 UNIQUE 约束(请参阅下面的代码),我会收到错误消息:错误:没有唯一约束与引用表“节点”的给定键匹配

所以我的问题是:为什么需要这个额外的唯一约束,有没有办法避免创建它? (以减少运行时开销)。

CREATE TABLE objects (
object_id serial NOT NULL PRIMARY KEY,
root_node integer
);

CREATE TABLE nodes (
node_id integer NOT NULL PRIMARY KEY,
object_id integer REFERENCES objects
);

ALTER TABLE objects
ADD CONSTRAINT root_node_fkey
FOREIGN KEY (root_node) REFERENCES nodes(node_id);

-- Why this constaint is needed? Since node_id is primary key this combination should be already UNIQUE
ALTER TABLE nodes ADD CONSTRAINT node_id_object_id_unique UNIQUE (node_id, object_id);

ALTER TABLE objects
ADD CONSTRAINT objects_nodes_fkey
FOREIGN KEY (object_id, root_node)
REFERENCES nodes (object_id, node_id);

最佳答案

https://www.postgresql.org/docs/current/static/ddl-constraints.html说:

5.3.5. Foreign Keys:

. . .

A foreign key must reference columns that either are a primary key or form a unique constraint. This means that the referenced columns always have an index (the one underlying the primary key or unique constraint); so checks on whether a referencing row has a match will be efficient.

https://mariadb.com/kb/en/sql-99/constraint_type-foreign-key-constraint/说:

A FOREIGN KEY Constraint is either a < Table Constraint> or a and defines a rule that constrains a foreign key to values that match only those values contained in a referenced unique key.


回复你的评论:

The idea is that each object will have collections of nodes associated with it and only one of nodes could be the root-node.

ALTER TABLE objects
ADD COLUMN root_node_id integer,
ADD CONSTRAINT objects_nodes_fkey
FOREIGN KEY (root_node_id)
REFERENCES nodes (node_id);

这样每个对象都只引用一个节点。不可否认,约束并没有严格强制一个对象引用一个引用同一对象的节点。

如果您想要那种级别的执行,您必须创建您所要求的唯一约束。

关于sql - 为什么需要这个 UNIQUE 约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41194495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com