小编典典

错误:引用表“bar”的给定键没有唯一约束匹配

all

尝试在 Postgres 9.1 中创建这个示例表结构:

CREATE TABLE foo (
    name        VARCHAR(256) PRIMARY KEY
);

CREATE TABLE bar (
    pkey        SERIAL PRIMARY KEY,
    foo_fk      VARCHAR(256) NOT NULL REFERENCES foo(name), 
    name        VARCHAR(256) NOT NULL, 
    UNIQUE (foo_fk,name)
);

CREATE TABLE baz(   
    pkey        SERIAL PRIMARY KEY,
    bar_fk      VARCHAR(256) NOT NULL REFERENCES bar(name),
    name        VARCHAR(256)
);

运行上面的代码会产生一个错误,这对我来说没有意义:

NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index

“foo_pkey” for table “foo”
NOTICE: CREATE TABLE will create implicit sequence “bar_pkey_seq” for
serial column “bar.pkey”
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index
“bar_pkey” for table “bar”
NOTICE: CREATE TABLE / UNIQUE will create implicit index
“bar_foo_fk_name_key” for table “bar”
NOTICE: CREATE TABLE will create implicit sequence “baz_pkey_seq” for
serial column “baz.pkey”
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index
“baz_pkey” for table “baz”
ERROR: there is no unique constraint matching given keys for referenced
table “bar”

********** Error **********

ERROR: there is no unique constraint matching given keys for referenced table "bar"
SQL state: 42830

谁能解释为什么会出现这个错误?


阅读 66

收藏
2022-06-09

共1个答案

小编典典

这是因为表name上的列bar没有 UNIQUE 约束。

因此,假设您在表上有 2 行bar包含名称,并且您在on
上插入'ams'一行,由于有两行匹配,它将引用哪一行?baz``'ams'``bar_fk``bar

2022-06-09