使用复合主键作为外键的问题

Issue on using composite primary key as a foreign key

我制作了一个复合键作为 table 航空公司的主键。 我想将该主键用作 table Flights 的外键。 我想要的是

的航班
  1. 两者都与航空公司无关,
  2. 或者如果是,则它们需要具有复合键的两列。

下面是tables:

CREATE TABLE Airlines (
  name char(32),
  country char(32),
  PRIMARY KEY (name, country)
);

CREATE TABLE Flights_operate (
  num integer PRIMARY KEY,
  dept timestamp,
  arr timestamp,
  name_Airlines char(32),
  country_Airlines char(32),
  CONSTRAINT FK
  FOREIGN KEY (name_Airlines, country_Airlines) REFERENCES Airlines (name, country)
);

我试过使用 CONSTRAINT,但似乎没有用。

我仍然可以插入带有 name_Airlines 而没有 country_Airlines 的行,如下所示: image

我该怎么办?

要仅禁止外键中的一列为空,您可以使用 MATCH FULL(参见 docs)。

CREATE TABLE Flights_operate (
  num integer PRIMARY KEY,
  dept timestamp,
  arr timestamp,
  name_Airlines char(32),
  country_Airlines char(32),
  CONSTRAINT FK
  FOREIGN KEY (name_Airlines, country_Airlines) 
  REFERENCES Airlines (name, country) MATCH FULL
);

您也可以使用 check 约束来执行此操作:

CREATE TABLE Flights_operate (
  num integer PRIMARY KEY,
  dept timestamp,
  arr timestamp,
  name_Airlines char(32),
  country_Airlines char(32),
  CONSTRAINT FK
  FOREIGN KEY (name_Airlines, country_Airlines) REFERENCES Airlines (name, country),
  CHECK (name_Airlines IS NOT NULL AND country_Airlines IS NOT NULL OR
         name_Airlines IS NULL AND country_Airlines IS NULL
        )
);

一些补充说明。

首先,不要使用 char 作为名称的数据类型。它用空格填充字符串,这通常是不可取的。

其次,考虑为所有表设置一个 identity/serial 主键。这比字符串更有效——考虑 4 个字节的整数和 64 个字节的复合键。