On this page
3.3. 外键
从Chapter 2调出weather
和cities
表。请考虑以下问题:您想确保没有人可以在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以获取更多信息。正确使用外键肯定会提高数据库应用程序的质量,因此强烈建议您学习它们。