Search code examples
mysqlsqlsql-updatemysql-error-1111

UPDATE a row with the SUM() and COUNT() of other rows


Imagine two tables like:

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

I want to do a query like this;

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

The query should update t1.sum with the sum of the values of t2 where t1.id=t2.id_t1 and t1.count with the count of rows there t1.id=t2.id_t1.

But fails and returns an error: ER_INVALID_GROUP_FUNC_USE: Invalid use of group function

How should I do that?


Solution

  • 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)