💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 3.3\. 外键 回忆一下[Chapter 2](#calibre_link-1350)里的`weather`和`cities`表。 考虑下面的问题:你想确保没有人可以在`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". ``` 外键的行为可以根据你的应用仔细调节。在这份教程里我们就不再多说了,请你参考[Chapter 5](#calibre_link-1570) 以获取更多的信息。正确使用外键无疑将改进你的数据库应用,所以我们强烈建议你学习它们。