支援的版本:目前 (17) / 16 / 15 / 14 / 13
開發版本:devel
不支援的版本:12 / 11 / 10 / 9.6 / 9.5 / 9.4 / 9.3 / 9.2 / 9.1 / 9.0 / 8.4 / 8.3 / 8.2 / 8.1 / 8.0 / 7.4 / 7.3 / 7.2

3.3. 外部鍵 #

回想一下weathercities表,出自第 2 章。考慮以下問題:您要確保沒有人可以在weather表中插入在cities表中沒有匹配條目的列。這被稱為維護您的資料的參考完整性。在簡化的資料庫系統中,這將透過(如果有的話)先查看cities表以檢查是否存在匹配的記錄,然後插入或拒絕新的weather記錄來實現。這種方法存在許多問題並且非常不方便,因此PostgreSQL可以為您執行此操作。

該表的新宣告應如下所示

CREATE TABLE cities (
        name     varchar(80) primary key,
        location point
);

CREATE TABLE weather (
        city      varchar(80) references cities(name),
        temp_lo   int,
        temp_hi   int,
        prcp      real,
        date      date
);

現在嘗試插入無效記錄

INSERT INTO weather VALUES ('Berkeley', 45, 53, 0.0, '1994-11-28');
ERROR:  insert or update on table "weather" violates foreign key constraint "weather_city_fkey"
DETAIL:  Key (city)=(Berkeley) is not present in table "cities".

可以針對您的應用程式對外部鍵的行為進行微調。在本教學中,我們將不會超出這個簡單的示例,而只是將您轉到第 5 章以獲取更多資訊。正確使用外部鍵肯定會提高資料庫應用程式的品質,因此強烈建議您學習它們。

提交更正

如果您在文件中看到任何不正確的內容、與您使用特定功能的經驗不符或需要進一步澄清,請使用此表單來報告文件問題。