使用其他行的SUM()和COUNT()更新一行

时间:2013-02-02 05:31:05

标签: mysql sql sql-update mysql-error-1111

想象一下两个表:

t1: id, sum, cnt 
t2: id, id_t1, value

我想做这样的查询;

UPDATE t1, t2 
   SET t1.sum = SUM(t2.value), 
       t1.cnt = COUNT(*) 
 WHERE t1.id = t2.id_t1;

查询应更新t1.sum,其中t2的值t1.id=t2.id_t1t1.count的值加上t1.id=t2.id_t1的行数。

但失败并返回错误:ER_INVALID_GROUP_FUNC_USE: Invalid use of group function

我该怎么做?

1 个答案:

答案 0 :(得分:6)

UPDATE  t1 a
        LEFT JOIN 
        (
            SELECT  id_t1, 
                    SUM(value) totalSum,
                    COUNT(*) totalCount
            FROM    t2
            GROUP BY id_t1
        ) b ON   a.ID = b.id_t1
SET a.sum = COALESCE(b.totalSum, 0) ,
    a.cnt = COALESCE(b.totalCount, 0)