我有一个系统余额表“A
”,其中“金额”列是借记/贷记列,如下所示:
id amount balance
1 100 100
2 -30 70
3 40 110
4 -20 90
如果新的存款是50美元,那么新行必须插入:
5 50 140
我可以通过选择上一次余额来实现这一目标:
SELECT id, balance
FROM A
ORDER BY id DESC LIMIT 1
然后插入新行:
INSERT INTO A (amount, balance)
VALUES (50, previous_balance+50)
但是,有没有办法只用一个查询来实现这个目的?它对大型数据库有效吗?谢谢!
答案 0 :(得分:1)
正确的做法是:
INSERT INTO A(amount,balance)
VALUES (50, 50 +
(SELECT B.balance
FROM(SELECT balance FROM A ORDER BY id DESC LIMIT 1) AS B)
);
因为mysql不能修改你在SELECT部分中使用的同一个表
答案 1 :(得分:0)
只需合并您的2个查询:
INSERT INTO A (amount, balance)
VALUES (50, (
SELECT balance
FROM (SELECT * from A)
ORDER BY id DESC LIMIT 1
)+50)
答案 2 :(得分:0)
您可以使用此查询:
INSERT INTO A (amount, balance)
SELECT "50", SUM(balance)
FROM ( SELECT id+1 as id, 50 balance FROM A
UNION ALL
SELECT id, balance FROM A
ORDER BY id DESC LIMIT 2
) t