我在接触到一个业务,是每15s更新 39718条数据,并且每一条数据都是来自很多不相同表,然后我用业务代码来做,执行时间在半个多小时,这远远超出了15s,于是用sql批量更新来处理了业务。sql只用了0.516s。
先准备两张表A,B。如下:
A:
B:
根据A表的t_name字段关联B表查询出t_name的个数。
SELECT a1.t_name, COUNT(a1.id) AS number FROM a AS a1 LEFT JOIN b ON a1.t_name = b.t_name GROUP BY a1.t_name
结果如下:
然后根据相同的字段t_name作为关联字段进行批量更新,如下:
UPDATE a SET a.t_value = ( SELECT t.number FROM ( SELECT a1.t_name, COUNT(a1.id) AS number FROM a AS a1 LEFT JOIN b ON a1.t_name = b.t_name GROUP BY a1.t_name ) t WHERE t.t_name = a.t_name )
执行结果:
当然还可以加入很多的条件更新,B表的t_status字段;我们只统计t_status为0的数据
SELECT a1.t_name, COUNT(a1.id) AS number FROM a AS a1 LEFT JOIN b ON a1.t_name = b.t_name WHERE b.t_status = 0 GROUP BY a1.t_name
结果如下:
UPDATE a SET a.t_value = ( IFNULL( (SELECT t.number FROM ( SELECT a1.t_name, COUNT(a1.id) AS number FROM a AS a1 LEFT JOIN b ON a1.t_name = b.t_name WHERE b.t_status = 0 GROUP BY a1.t_name ) t WHERE t.t_name = a.t_name) ,0))
结果如下:
结果出现了空的值,但是我想变为0那就用ifnull,如下
UPDATE a SET a.t_value = ( IFNULL( (SELECT t.number FROM ( SELECT a1.t_name, COUNT(a1.id) AS number FROM a AS a1 LEFT JOIN b ON a1.t_name = b.t_name WHERE b.t_status = 0 GROUP BY a1.t_name ) t WHERE t.t_name = a.t_name) ,0))
结果:
如有什么问题和建议,欢迎讨论和留言。