如何在 PostgreSQL 中添加外键

Eri*_*eon 20 postgresql database-design constraints foreign-keys primary-key

我创建了第一个名为“bookstore”的表,其中主键是 book_name:

create table bookstore (book_name varchar primary key, author varchar, price decimal);
Run Code Online (Sandbox Code Playgroud)

我正在尝试创建第二个名为“名称”的表,其中名称是主键。我想将这个主键author.name作为bookstore.author的外键。

create table author (name varchar primary key, place varchar,
                    constraint fk_author_bookstore foreign key(name) references bookstore(author));
Run Code Online (Sandbox Code Playgroud)

但错误是:错误:没有与引用表“bookstore”的给定键匹配的唯一约束 SQL 状态:42830

我是 SQL 新手,所以希望能得到一些帮助。如果可以的话,请写出正确的代码。谢谢

Rah*_*was 34

作者表中的名称列是主键,在书店表中作为外键引用。

-- PostgreSQL (v11)

create table author (name varchar primary key, place varchar);

create table bookstore (book_name varchar primary key, author varchar, price decimal
, CONSTRAINT fk_author_bookstore
      FOREIGN KEY(author) 
      REFERENCES author(name));
Run Code Online (Sandbox Code Playgroud)

请从网址https://dbfiddle.uk/?rdbms=postgres_11&fiddle=8394f796433ed8bc170c2889286b3fc2检查

创建表后添加外键

-- PostgreSQL(v11)
ALTER TABLE bookstore
      ADD CONSTRAINT fk_author_bookstore FOREIGN KEY (author) 
          REFERENCES author (name);
Run Code Online (Sandbox Code Playgroud)

请从网址检查https://dbfiddle.uk/?rdbms=postgres_11&fiddle=d93cf071bfd0e3940dfd256861be813c

  • 谢谢,我现在明白了。 (2认同)