且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySQL使用带有多个返回行的子查询更新字段值

更新时间:2023-11-09 21:06:46

可能有必要确保您的UPDATE语句尝试将每个用户的行仅更新一次.子查询是执行此操作的***方法,可以最有效地实现为联接表:

It's probably worthwhile to ensure that your UPDATE statement is trying to update each user's row exactly once. A subquery is the best way to do this, most efficiently implemented as a joined table:

UPDATE bank 
JOIN (SELECT LOWER(bonds.holder) as user,
    SUM(bonds.issuePrice * bonds.coupon) as total
    FROM bonds
    WHERE LOWER(bonds.holder) != 'bank'
    GROUP BY user
) as increments ON increments.user = LOWER(bank.user)
SET bank.cash = ROUND(bank.cash + increments.total, 2),
    bank.earned = ROUND(bank.earned + increments.total, 2)

(为获得更多优化,应该消除LOWER和ROUND调用,但这是另一种讨论.)

(For more optimization, the LOWER and ROUND calls should probably be eliminated, but that's another discussion.)