3.3. 外鍵

回憶一下 Chapter 2 裡的 weathercities 資料表。考慮一下下面的問題:您想確保沒有人可以在 weather 資料表裡插入一條在 cities 資料表裡沒有匹配記錄的資料行。 這就叫維護您的資料表的參考完整性。 在簡單的資料庫系統裡,實現(如果也叫實現)這個特性的方法 通常是先看看 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".

外鍵的行為可以為您的應用仔細調節。在這份教學裡我們就不再多說了,而是請您參考Chapter 5獲取更多的訊息。 正確使用外鍵無疑將改進您的資料庫應用,所以我們強烈建議您學習它們。