?
本文檔使用
php中文網手冊 發(fā)布
回憶一下Chapter 2里的weather
表
和cities
表。
考慮下面的問題:
你想確保沒有人可以在weather
表里插入一條
在cities
表里沒有匹配記錄的數(shù)據(jù)行。
這就叫維護表的參照完整性。
在簡單的數(shù)據(jù)庫系統(tǒng)里,
實現(xiàn)(如果也叫實現(xiàn))這個特性的方法通常是先看看
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".
外鍵的行為可以根據(jù)你的應用仔細調節(jié)。 在這份教程里我們就不再多說了, 請你參考Chapter 5以獲取更多的信息。 正確使用外鍵無疑將改進你的數(shù)據(jù)庫應用,所以我們強烈建議你學習它們。