wangchaovsjava 发表于 2013-1-30 01:30:44

SQL外键的应用

外键
考虑下面的问题:你想确保没有人可以在 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".外键的行为可以根据你的应用仔细调节。在这份教程里我们就不再多说了,正确使用外键无疑将改进你的数据库应用,所以我们强烈建议你学习它们。
页: [1]
查看完整版本: SQL外键的应用