Redrock Postgres 搜索 英文
版本: 9.3 / 9.4 / 9.5 / 9.6 / 10 / 11 / 12 / 13 / 14 / 15 / 16 / 17

3.3. 外键 #

第 2 章 回想一下 weathercities 表格。思考以下问题:您希望确保没人能向 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 章 以了解更多信息。正确使用外键肯定会提高数据库应用程序的质量,因此强烈建议您了解它们。