3.3 外键
大约 1 分钟
假设一种情况:您希望确保没有人可以在 weather 表中插入在 cities 表中没有匹配条目的行。
这称为维护数据的引用完整性。在简单的数据库系统中,这将通过首先查看 cities 表以检查是否存在匹配的记录,然后插入或拒绝新的 weather 记录来实现(如果有的话)。
这种方法有很多问题,而且非常不方便,所以 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".
正确的使用外键将有效提高应用程序的质量,我们需要了解它。