从子查询更新多个列

时间:2013-05-10 00:37:55

标签: mysql sql

此类事情之前曾被问过几次,但并不是我想要的。我需要SET两行等于子查询的不同部分。

我目前正在使用:

UPDATE records
SET leads=(SELECT COUNT(*) FROM leads_table WHERE leads_table.blah=records.blah),
earnings=(SELECT SUM(amount) FROM leads_table WHERE leads_table.blah=records.blah)

WHERE语句显然被简化了......但基本上它是相同的子查询但是我不认为我应该运行它两次?

我想做点像......

UPDATE records
SET (leads,earnings)=(SELECT COUNT(*),SUM(amount) FROM leads_table WHERE leads_table.blah=records.blah)

1 个答案:

答案 0 :(得分:31)

您可以简单地将表连接到执行某些计算的子查询中,

UPDATE  records a
        INNER JOIN
        (
            SELECT  blah, 
                    COUNT(*) totalCount,
                    SUM(amount) totalSum
            FROM    leads_table
            GROUP   BY blah
        ) b ON  b.blah = a.blah
SET     a.leads = b.totalCount
        a.earnings = b.totalSum