15.6. Lesson: 规则

规则允许重写传入查询的“查询树”。一种常见的用法是实现视图,包括可更新的视图。 - Wikipedia

The goal for this lesson: 学习如何为数据库创建新规则。

15.6.1. 创建日志记录规则

假设您想要将People表中Phone_no的每次更改记录到People_LOG表中。因此,您设置了一个新的表:

create table people_log (name text, time timestamp default NOW());

在下一步中,创建一条规则,将People表中phone_no的每次更改记录到People_log表中:

create rule people_log as on update to people
  where NEW.phone_no <> OLD.phone_no
  do insert into people_log values (OLD.name);

为了测试该规则是否有效,让我们修改一个电话号码:

update people set phone_no = '082 555 1234' where id = 2;

检查是否有 people 表已正确更新:

select * from people where id=2;

 id |    name    | house_no | street_id |   phone_no
----+------------+----------+-----------+--------------
  2 | Joe Bloggs |        3 |         2 | 082 555 1234
(1 row)

现在,由于我们创建的规则, people_log 表格将如下所示:

select * from people_log;

    name    |            time
------------+----------------------------
 Joe Bloggs | 2014-01-11 14:15:11.953141
(1 row)

备注

它的价值在于 time 字段将取决于当前日期和时间。

15.6.2. In Conclusion

规则允许您自动添加或更改数据库中的数据,以反映数据库其他部分的更改。

15.6.3. What's Next?

下一个模块将向您介绍使用PostGIS的空间数据库,它采用了这些数据库概念,并将它们应用于GIS数据。