concat和outfile妙用
在紧急线上场景(产品bug、数据错乱)中,常需要从备份库等其他库挖出一批数据,作为在线库执行 SQL 的条件。传统做法是先导出 id,再用脚本或手工循环拼接 SQL,数据量稍大就很痛苦。文章给出的技巧是用 concat + into outfile 直接生成可执行的 SQL 脚本:例如先在重现备份数据的服务器上执行 select concat('update garbage set data=value where id=',id,' and num=value;') from user into outfile '/tmp/a.txt',检查生成的文件后,在线上服务器用 source /tmp/a.txt 批量执行即可,免去脚本拼接的麻烦。
同理该方法还可用于批量杀掉 processlist 中的某些连接:select concat('KILL ',id,';') from information_schema.processlist into outfile '/tmp/kill.txt' 再 source 执行,还能加 where 条件过滤特定类型的连接。虽然 maatkit 也有类似工具,但用 MySQL 自身完成更方便,事半功倍。