我正在使用 PostgreSQL,但我认为大多数高端数据库必须具有一些类似的功能,而且,它们的解决方案可能会启发我的解决方案,所以不要考虑这个特定于 PostgreSQL 的解决方案。
我知道我不是第一个尝试解决这个问题的人,所以我认为这里值得一问,但我正在尝试评估建模会计数据的成本,以便从根本上平衡每笔交易。会计数据是仅附加的。此处的总体约束(以伪代码编写)可能大致如下:
CREATE TABLE journal_entry (
id bigserial not null unique, --artificial candidate key
journal_type_id int references journal_type(id),
reference text, -- source document identifier, unique per journal
date_posted date not null,
PRIMARY KEY (journal_type_id, reference)
);
CREATE TABLE journal_line (
entry_id bigint references journal_entry(id),
account_id int not null references account(id),
amount numeric not null,
line_id bigserial not null unique,
CHECK ((sum(amount) over (partition by entry_id) = 0) -- this won't work
);
Run Code Online (Sandbox Code Playgroud)
显然,这样的检查约束永远不会起作用。它按行操作,可能会检查整个数据库。所以它总是会失败并且做起来很慢。
所以我的问题是对这种约束进行建模的最佳方法是什么?到目前为止,我基本上已经研究了两个想法。想知道这些是否是唯一的,或者是否有人有更好的方法(除了将其留给应用程序级别或存储过程)。