想象一下两个表:
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_t1
和t1.count
的值加上t1.id=t2.id_t1
的行数。
但失败并返回错误:ER_INVALID_GROUP_FUNC_USE: Invalid use of group function
我该怎么做?
答案 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)