天天看點

PostgreSQL 10.1 手冊_部分 I. 教程_第 3 章 進階特性_3.3. 外鍵

3.3. 外鍵

回想第2章中的

weather

cities

表。考慮以下問題:我們希望確定在

cities

表中有相應項之前任何人都不能在

weather

表中插入行。這叫做維持資料的引用完整性。在過分簡化的資料庫系統中,可以通過先檢查

cities

表中是否有比對的記錄存在,然後決定應該接受還是拒絕即将插入

weather

表的行。這種方法有一些問題且并不友善,于是PostgreSQL可以為我們來解決:

新的表定義如下:

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

CREATE TABLE weather (
        city      varchar(80) references cities(city),
        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 章

中的資訊。正确使用外鍵無疑會提高資料庫應用的品質,是以強烈建議使用者學會如何使用它們。

本文轉自PostgreSQL中文社群,原文連結: