从没有主键的其他表中删除相关行

时间:2013-11-17 05:04:11

标签: sql postgresql

当删除船员时,我需要从“assign”表中删除相关的行。

但是,当我创建表时,我收到错误:

ERROR:  there is no unique constraint matching given keys for referenced table "assign"

似乎我需要在“assign”表中使用不同的值,但重点是我要删除机组成员时删除所有相关信息。我怎么能这样做?

create table flight(
  flight_num BIGSERIAL PRIMARY KEY,
  source_city varchar,
  dest_city varchar,
  dep_time int,
  arr_time int,
  airfare int,
  mileage int
);

create table crew (
  id BIGSERIAL PRIMARY KEY,
  name varchar,
  salary int,
  position varchar,
  seniority int,
  fly_hours int,
  mgrid int,
  FOREIGN KEY (id) REFERENCES assign(id) ON DELETE CASCADE
);

create table assign (
  id int, # refers to a crew member id, not a row id
  flight_num int
);

1 个答案:

答案 0 :(得分:3)

外键应该在M-M连接表上,如下:

create table flight(
  flight_num int PRIMARY KEY,
  -- etc
);

create table crew (
  crew_id int PRIMARY KEY,
  -- etc
);

create table assign (
  crew_id int,
  flight_num int,
  -- If the corresponding record in either of these FKs is deleted then
  -- this record will be deleted.
  FOREIGN KEY (crew_id) REFERENCES crew(crew_id) ON DELETE CASCADE,
  FOREIGN KEY (flight_num) REFERENCES flight(flight_num) ON DELETE CASCADE,
  -- M-M usually should have a PK over both foreign columns, arranged in order
  -- of expected usage. A reverse covering index can be added if needed.
  PRIMARY KEY (flight_num, crew_id)
);

在这种情况下,允许使用FK,因为它们位于唯一列(crewflight的PK)之上。原始错误是因为FK目标(assign.crew_id)没有唯一的约束。