最近接到一个任务,公司可能前期规划问题,没人设计表结构及使用方法,把好多数据放到了一张表里面,造成了单表超级大的问题,给查询和转储造成很大麻烦。
需求:要把表二(第二张图)的数据和第一张表中的做比对,匹配上的话 ,放另外一张表里面
如果表都比较小,一行 sql 做个join 然后插入就可以了,但是这个表数据量太大了,数据库配置又比较低,这样做数据库会卡死。
我的小想法,如下:
前提:把两张表要关联的字段加上合适的索引。表二有一个自增 id
1、先查出第二张的记录数 n
2、每次一万条进行处理 n/10000 加1 是循环次数 找到 id 的区间范围,比如第一次是 (0,10000 ] 每次均采取左开右闭 的范围防止重复计算,然后做连接查询,把结果放入到临时文件
如
select b.* from table1 a,table2 b where id > startindex and id <= endindex and a.f1=b.f1 and a.f2=b.f2
用shell 执行上面sql 把结果放入中间文件
mysql -h'主机' -P'3306' -u'用户名' -p'密码' --default-character-set=utf8 -e"select b.* from table1 a,table2 b where id > startindex and id <= endindex and a.f1=b.f1 and a.f2=b.f2” >temp_$i
3、循环完毕后,插入新数据库表
for file in ./temp_*
do
echo $file
mysql -h'主机' -P'3306' -u'用户名' -p'密码' --default-character-set=utf8 -e"load data local infile '$file' into table 库.新表名 fields terminated by '\t' lines terminated by '\n'"
#rm -rf $file
done
大功告成,时间也需要的挺长,喝茶等着结果就行