简体   繁体   English

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

[英]Issue on using composite primary key as a foreign key

I have made a composite key as a primary key for table Airlines.我已经制作了一个复合键作为表航空公司的主键。 And I want to use that primary key as a foreign key for table Flights.我想将该主键用作表航班的外键。 With that what I want is to have Flights that有了这个,我想要的是有航班

  1. that either are not related to Airlines,与航空公司无关,
  2. or if they are, they need to have both columns of the composite key.或者,如果是,则它们需要具有组合键的两列。

Below are 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)
);

I tried using CONSTRAINT but it doesn't seem to do the trick.我尝试使用CONSTRAINT但它似乎没有用。

I can still insert rows with a name_Airlines and without a country_Airlines like so: image我仍可以插入一个行name_Airlines并没有country_Airlines像这样:图片

What should I do?我该怎么办?

To disallow just one of the columns in the foreign key from being null, you can use MATCH FULL (see docs ).要仅禁止外键中的一列为空,您可以使用 MATCH FULL(请参阅文档)。

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
);

You can also do this using a check constraint:您也可以使用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
        )
);

Some additional notes.一些附加说明。

First, do not use char as a data type for names.首先,不要使用char作为名称的数据类型。 It pads the strings with spaces, which is generally undesirable.它用空格填充字符串,这通常是不可取的。

Second, consider having an identity/serial primary key for all your tables.其次,考虑为所有表设置一个身份/串行主键。 This is more efficient than strings -- consider 4 bytes for an integer versus 64 bytes for your composite key.这比字符串更有效——考虑 4 个字节的整数与 64 个字节的复合键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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