9.3 9.4 9.5 9.6 10 11 12 13
阿里云PostgreSQL 问题报告 纠错本页面

3.3. 外键

回忆一下第 2 章里的weathercities表。 考虑下面的问题:你想确保没有人可以在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".

外键的行为可以根据你的应用仔细调节。在这份教程里我们就不再多说了,请你参考第 5 章 以获取更多的信息。正确使用外键无疑将改进你的数据库应用,所以我们强烈建议你学习它们。

<
/BODY >