2025年9月25日: PostgreSQL 18 发布!
支持的版本: 当前 (18) / 17 / 16 / 15 / 14 / 13
开发版本: devel
不支持的版本: 12 / 11 / 10 / 9.6 / 9.5 / 9.4 / 9.3 / 9.2 / 9.1 / 9.0 / 8.4 / 8.3 / 8.2 / 8.1 / 8.0 / 7.4 / 7.3 / 7.2

3.3. 外键 #

回想一下 第二章 中的 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".

外键的行为可以根据您的应用程序进行精细调整。在本教程中,我们将不超出这个简单的示例,而是引用 第五章 以获取更多信息。正确使用外键肯定会提高您的数据库应用程序的质量,因此强烈建议您了解它们。

提交更正

如果您在文档中看到任何不正确、与您对特定功能的经验不符或需要进一步澄清的内容,请使用 此表单 来报告文档问题。