Foreign Keys

3.3. Foreign Keys

Recall the weather and cities tables from Chapter 2. Consider the following problem: You want to make sure that no one can insert rows in the weather table that do not have a matching entry in the cities table. This is called maintaining the referential integrity of your data. In simplistic database systems this would be implemented (if at all) by first looking at the cities table to check if a matching record exists, and then inserting or rejecting the new weather records. This approach has a number of problems and is very inconvenient, so PostgreSQL can do this for you.

The new declaration of the tables would look like this:

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

);

Now try inserting an invalid record:

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".

The behavior of foreign keys can be finely tuned to your application. We will not go beyond this simple example in this tutorial, but just refer you to Chapter 5 for more information. Making correct use of foreign keys will definitely improve the quality of your database applications, so you are strongly encouraged to learn about them.

3.3 外键

第二章节中使用的weather和cities表。考虑如下问题:你需要确认,在cities表中没有的城市,不能在weather表中有天气信息。这叫做维护你数据的引用完整性。在一些不太专业的数据库中,这种限制是通过以下方式实现的:首先查询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章以获取更多的相关信息。 正确使用外键可显著提高您数据库应用程序的质量,所以强烈建议您进一步学习它们。

发布了341 篇原创文章 · 获赞 53 · 访问量 88万+

猜你喜欢

转载自blog.csdn.net/ghostliming/article/details/103400144
今日推荐