[英]Issue on using composite primary key as a foreign key
我已經制作了一個復合鍵作為表航空公司的主鍵。 我想將該主鍵用作表航班的外鍵。 有了這個,我想要的是有航班
以下是表格:
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
像這樣:圖片
我該怎么辦?
要僅禁止外鍵中的一列為空,您可以使用 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
);
您也可以使用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
作為名稱的數據類型。 它用空格填充字符串,這通常是不可取的。
其次,考慮為所有表設置一個身份/串行主鍵。 這比字符串更有效——考慮 4 個字節的整數與 64 個字節的復合鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.