我的查询。
UPDATE assets SET assets.Amount = (SELECT SUM(assets.Amount) - NEW.Amount FROM assets WHERE NEW.UserId = assets.UserId and NEW.AccountId = assets.AccountId) AS TmpAssets
WHERE NEW.UserId = assets.UserId and NEW.AccountId = assets.AccountId
答案 0 :(得分:1)
MySQL不允许您在update
或delete
的子查询中使用正在更新的表。这很容易解决这个问题。
以下是使用update
/ join
的一种方法:
UPDATE assets a JOIN
(select sum(a.Amount) as sumamount, a.UserId, a.AccountId
from assets a
where NEW.UserId = a.UserId and NEW.AccountId = a.AccountId
group by a.UserId, a.AccountId
) anew
on NEW.UserId = a.UserId and NEW.AccountId = a.AccountId
SET a.Amount = anew.sumamount - new.Amount;
答案 1 :(得分:0)
是的,你不能这样做,因为你在更新它时从表中进行子选择。 你可以做的最好的事情是创建一个tmp表并执行它们的子查询。
答案 2 :(得分:0)
试试这个:
UPDATE assets SET assets.Amount = (select temp.val from (SELECT (SUM(assets.Amount) -
NEW.Amount) val from assets WHERE
NEW.UserId = assets.UserId and NEW.AccountId = assets.AccountId) temp)
WHERE NEW.UserId = assets.UserId and NEW.AccountId = assets.AccountId ;