b表: id -->主键,自增id reason ->电话通话失败的原因 sessionid -->唯一标志一通电话的标记位 create_time -->记录创建时间
a表记录大概50W条,b表记录大概20w条,且b表中存在sessionid重复的记录 由于某些原因,电话失败原因不能通过a表关联b表查询得到,而要定期(30分钟或1个小时)从b表更新到a表中,这个更新语句该如何写效率最高? 最初我的写法是这样: update a表 t set t.fail_reason = (SELECT t2.reason from b表 t2 where t.sessionid = t2.sessionid and t.status = 2 order by t2.create_time desc limit 0,1 ) where t.status = 2 and UNIX_TIMESTAMP() -t.send_time < 3600 and (t.fail_reason = '' or t.fail_reason is null) ------------- 以上语句写成数据库事件,每隔半个小时执行一次,后期随着数据增大,感觉效率非常低,执行一次最少都几十分钟, 后来百度google到另一种写法: update a表 t ,b表 t2 set t.fail_reason=t2.reason where t.sessionid=t2.sessionid and t.status=2 and UNIX_TIMESTAMP() -t.send_time < 3600 and (t.fail_reason = '' or t.fail_reason is null) 但还是很慢
TRUNCATE TABLE t3; INSERT INTO t3 (SELECT sessionid, reason FROM (SELECT sessionid,reason FROM t2 ORDER BY create_time DESC) as t22 GROUP BY sessionid); UPDATE t,t3 SET ... WHERE ...