sql - 错误 : there is no unique constraint matching given keys for referenced table "bar"

标签 sql postgresql foreign-keys unique-constraint

尝试在 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

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

最佳答案

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

假设您在 bar 上有 2 行包含名称 'ams' 的表然后在 baz 上插入一行与 'ams'bar_fk , 哪一行在 bar 上是指因为有两行匹配吗?

关于sql - 错误 : there is no unique constraint matching given keys for referenced table "bar",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11966420/

相关文章:

python - sqlalchemy 在多个表上联接和排序

mysql - 无法使用 phpMyAdmin 在关系 View 中设置关系

mysql - SUM 相关表中的时间值

sql - 比较行之间的值

sql - 如何使用 PL/pgSQL 构建具有动态列的表

MySQL 错误 150

mysql - 跟踪 mysql 更改的最佳方法

php - mysql insert ignore, replace or update on duplicate - 插入了吗?

Postgresql索引seq扫描1亿行

php - 将Adodb用于php/postgresql,插入后返回行ID