我有一个包含列的表:借记,贷记,借记平衡,信用余额和金额。借方和贷方均与特定账户有关。
每次添加新行时,我都希望根据帐户之前的余额分配debit_balance和credit_balance。
INSERT INTO `ledger` (`debit`, `credit`, `debit_balance`, `credit_balance`, `amount`)
VALUES ('1', '3',
(SELECT debit_balance FROM `ledger` WHERE `debit` = '1' ORDER BY `id` DESC LIMIT 0,1) + 5,
(SELECT credit_balance FROM `ledger` WHERE `credit` = '3' ORDER BY `id` DESC LIMIT 0,1) + 5,
'5')
如果借记卡的帐户为1,则信用卡的帐户为3,我想要更改的金额为5。
当我运行查询时,mysql给出了Every derived table must have its own alias
错误。
答案 0 :(得分:1)
您可以使用单个SELECT
查询来提供要插入的值。
INSERT INTO ledger (debit, credit, debit_balance, credit_balance, amount)
SELECT 1, 3, l1.debit_balance + 5, l2.credit_balance + 5, 5
FROM (SELECT MAX(id) AS debit_id FROM ledger WHERE debit = 1) AS maxd
JOIN ledger AS l1 ON l1.id = maxd.debit_id
CROSS JOIN (SELECT MAX(id) AS credit_id FROM ledger WHERE credit = 3) AS maxc
JOIN ledger AS l2 ON l2.id = maxc.credit_id