# 3.3.外键
回想一下天气
和城市
来自第二章请考虑以下问题:要确保没有人可以在天气
表中没有匹配项的城市
桌子这叫做维护参照完整性你的数据。在过于简单的数据库系统中,这将通过首先查看城市
表来检查是否存在匹配的记录,然后插入或拒绝新记录天气
记录。这种方法有很多问题,而且非常不方便,所以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".
外键的行为可以根据应用程序进行微调。在本教程中,我们将不讨论这个简单的例子,而只是让您参考第五章了解更多信息。正确使用外键肯定会提高数据库应用程序的质量,因此强烈建议您了解它们。