mysql连表inner join聚合查询更新,一个标准场景案例
mysql连表inner join聚合查询更新,一个标准场景案例
场景:两个表t1,t2 ,1对多, t1表一个字段记录t2表对应t1表关联id的总条数,写一个定时任务,事件每天凌晨1天更新。
1.查询出来inner join t1表id对应t2表的总条数
SELECT
t1.id,
count( t2.qid ) AS num
FROM
lara_t1 AS t1
INNER JOIN lara_t2 AS t2 ON t1.id = t2.qid
GROUP BY
t2.qid
查询结果:
id | num
32921
32931
32951
32964
32971
32983
32991
33001
33011
2.根据上面查询的结果根据id直接把num更新到t1表特定字段中
UPDATE lara_t1 AS t
INNER JOIN (
SELECT
t1.id,
count( t2.qid ) AS num
FROM
lara_t1 AS t1
INNER JOIN lara_t2 AS t2 ON t1.id = t2.qid
GROUP BY
t2.qid
) t3 ON t.id = t3.id
SET t.AnswerCount = t3.num
直接执行 完成
> Affected rows: 751112
> 时间: 3.238s
mysql事件添加可以自行查询我之前的文章
相关文章