回想一下 第 2 章 中的 weather
和 cities
表。考虑以下问题:您要确保无法在 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".
外键的行为可以针对您的应用程序进行微调。在本教程中,我们不会超出这个简单的示例,但只需参考第 5 章即可了解更多信息。正确使用外键肯定会提高数据库应用程序的质量,因此强烈建议您了解它们。