在 PostgreSQL 中实施多 table 数据库逻辑

Enforce multi-table database logic in PostgreSQL

有没有办法强制执行跨越 table 的数据库逻辑?作为一个非常非常简单的超级缩减示例,想象一个双 table 发票系统:

create table accounts (id serial primary key, balance integer not null default 0);
create table invoices (id serial primary key, acct integer references accounts, total integer not null);

开具发票包括在发票中插入一行 table,并使用新余额更新帐户 table。 (是的,我知道这里存在规范化问题,但还有其他原因希望余额在主要 table 中。此外,这过于简单化了。)

这里有一个不变量:对于任何给定的帐户,(select balance from accounts where id=N)==(select sum(total) from invoices where acct=N) - 或者,换句话说,select acct,sum(total) from invoices group by acct 应该与 select id,balance from accounts 相同(尽管后者将有没有发票的为零)。

有没有办法在 PostgreSQL 中强制执行此操作?我宁愿不必信任客户端代码。

我想你还需要一个触发器。捕获 Before Insert 或 After Insert 事件,以及 Before Update 或 After Update 事件。 (我以前抓过,但出于便携性的原因现在我抓住了之后) 在插入和更新时,您还更新了您需要的所有列。 下面是如何构建触发器: