简体   繁体   中英

PostgreSQL: Composite Primary Keys: no unique constraint matching given keys

Why does the following return there is no unique constraint matching given keys for referenced table "cats" ?

CREATE TABLE cats (
  name varchar(36) NOT NULL,
  owner_id varchar(36) NOT NULL REFERENCES owners (id) ON DELETE CASCADE ON UPDATE CASCADE,
  description varchar(255) NOT NULL DEFAULT '',

  PRIMARY KEY (name, owner_id)
);

I could do ...

CREATE TABLE cats (
  name varchar(36) NOT NULL,
  owner_id varchar(36) NOT NULL REFERENCES owners (id) ON DELETE CASCADE ON UPDATE CASCADE,
  description varchar(255) NOT NULL DEFAULT '',

  PRIMARY KEY (name, owner_id),
  UNIQUE (name),
  UNIQUE (owner_id)
);

which doesn't return any error. But this means that cat names can't be given twice (or more) by different cat owners?

Basically, this is what I want:

cats.name | cats.owner  
DAISY     | BOB
NALA      | BOB
NALA      | CARL

When I run the create, I get the following error:

Schema Creation Failed: ERROR: column "id" named in key does not exist:

You need to define the columns used in the primary key.

Using name does seem to fix the problem:

CREATE TABLE cats (
  name varchar(36) NOT NULL,
  owner_id varchar(36) NOT NULL REFERENCES owners (id) ON DELETE CASCADE ON UPDATE CASCADE,
  description varchar(255) NOT NULL DEFAULT '',

  PRIMARY KEY (name, owner_id)
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM