[英]Why do I get a foreign key not unique error on an identity column?
If I try to create two tables like this in PostgreSQL 14.3:如果我尝试在 PostgreSQL 14.3 中创建两个这样的表:
CREATE TABLE IF NOT EXISTS foo (
id INT4 GENERATED BY DEFAULT AS IDENTITY (INCREMENT BY 1 MINVALUE -2147483648 START -2147483648),
foo TEXT UNIQUE NOT NULL
);
CREATE TABLE IF NOT EXISTS bar (
id INT4 GENERATED BY DEFAULT AS IDENTITY (INCREMENT BY 1 MINVALUE -2147483648 START -2147483648),
foo_id INT4 NOT NULL REFERENCES foo(id)
);
I get this output:我得到这个 output:
$ psql test -f bug01.sql
CREATE TABLE
psql:bug01.sql:9: ERROR: there is no unique constraint matching given keys for referenced table "foo"
I thought GENERATED BY DEFAULT AS IDENTITY
would have satisfied the uniqueness constraint.我认为
GENERATED BY DEFAULT AS IDENTITY
会满足唯一性约束。 What am I missing?我错过了什么? And how do I resolve the issue?
我该如何解决这个问题?
UPDATE: Applying Bergi's answer and comments, I added a primary key constraint to each identity column and that solved the problem:更新:应用 Bergi 的回答和评论,我向每个标识列添加了一个主键约束并解决了问题:
CREATE TABLE IF NOT EXISTS foo (
id INT4 PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY (INCREMENT BY 1 MINVALUE -2147483648 START -2147483648),
foo TEXT UNIQUE NOT NULL
);
CREATE TABLE IF NOT EXISTS bar (
id INT4 PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY (INCREMENT BY 1 MINVALUE -2147483648 START -2147483648),
foo_id INT4 NOT NULL REFERENCES foo(id)
);
$ psql test -f bug01.sql
CREATE TABLE
CREATE TABLE
Thanks!谢谢!
Well, no.好吧,不。
GENERATED
just means it's harder to overwrite (requiring special syntax) than a DEFAULT
value, and AS IDENTITY
is just a fancy way of defining an implicit sequence, similar to SERIAL
.GENERATED
只是意味着它比DEFAULT
值更难覆盖(需要特殊语法),而AS IDENTITY
只是一种定义隐式序列的奇特方式,类似于SERIAL
。
You still can insert duplicates in your column, either by resetting the sequence or using OVERRIDING SYSTEM VALUE
, you must declare the appropriate constraints to prevent this.您仍然可以通过重置序列或使用
OVERRIDING SYSTEM VALUE
在您的列中插入重复项,您必须声明适当的约束以防止这种情况发生。 Simply make your id
the PRIMARY KEY
of the table.只需将您的
id
设为表的PRIMARY KEY
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.