gpt4 book ai didi

mysql:基于另外两行的值运行插入

转载 作者:行者123 更新时间:2023-11-29 11:38:41 25 4
gpt4 key购买 nike

我有一个包含以下列的表:借方、贷方、debit_balance、credit_balance 和 amount。借方和贷方各自属于特定帐户。

每次添加新行时,我都希望根据帐户之前的余额分配 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 给我一个每个派生表必须有自己的别名错误。

最佳答案

您可以使用单个 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

关于mysql:基于另外两行的值运行插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36189275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com