尝试使行保持一致,然后引用之前的行。
CREATE TABLE transactions (
id int PRIMARY KEY
GENERATED BY DEFAULT AS IDENTITY,
account_id bigint REFERENCES account,
change integer NOT NULL,
balance integer NOT NULL,
)
来自客户端的查询基本上是
SELECT balance
FROM transactions
WHERE account_id = X
ORDER BY id DESC
LIMIT 1;
INSERT INTO transactions (account_id, change, balance)
VALUES (X, 100, $balance + 100);
此代码将在并发插入时产生不正确的结果。那么,问题是如何让余额计算永远正确呢?
会INSERT INTO ... SELECT(...)
够吗?