18

这种类型的东西以前被问过几次,但不是我想要的。我需要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)
4

1 回答 1

44

您可以简单地将表加入到执行一些计算的子查询中,

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
于 2013-05-10T00:42:02.950 回答