有两个表 a , b 通过id关联
现在要把 b 表里有而a 表里没有的记录,存入a
用的语句insert into a
select a.*
from a
left join b on a.id = b.id
where b.user_id is null感觉慢,有没有快的办法
两个表的id都是主键
现在要把 b 表里有而a 表里没有的记录,存入a
用的语句insert into a
select a.*
from a
left join b on a.id = b.id
where b.user_id is null感觉慢,有没有快的办法
两个表的id都是主键
解决方案 »
- 有什么办法从远程机器通过3306端口导出整个数据库内容?
- 中间表问题
- mysql在命令行启动报错
- 求解:Mysql使用utf8字符集插入中文乱码
- *** 高分请教:MySQL的问题,请注意不是SQLServer ***
- 好像一些配置信息都在名为mysql的库里,例如用户名基访问权限之类的,有这方面的参考资料么,请给个连接?
- 我进mysql的密码忘了,请问有什么办法可以重新设置新密码
- postgres中如何检查一张表的某个字段是否已经存在?
- 请教mysql的导出导入问题
- mysql查询问题
- 求救关于mysql查询Sending data时间过长引起数据库卡死问题
- MYSQL编码方式问题.高手帮我一下.
2 alter table a disable keys
3 排序插入
insert into a
select a.*
from a
left join b on a.id = b.id
where b.user_id is null
已经去掉A、B中相同的ID了你生成TXT文件,SELECT INTO OUTFILE,再LOAD进A表试试
下面这句并不实现你的这个要求!insert into a
select a.*
from a
left join b on a.id = b.id
where b.user_id is null
改为
insert into a
select b.*
from b
left join a on a.id = b.id
where a.user_id is null或者
insert into a
select * from b where id not in (select id from a);
至少效率问题,建议你出你的以下结果以供分析。explain insert into a
select * from b where id not in (select id from a);
explain insert into a
select b.*
from b
left join a on a.id = b.id
where a.user_id is null;
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE a ALL NULL NULL NULL NULL 31656
1 SIMPLE b ALL PRIMARY NULL NULL NULL 31680 Using where; Not exists ----not in 的
1 PRIMARY cylkhwx_yhzl ALL NULL NULL NULL NULL 31656 Using where
2 DEPENDENT SUBQUERY t_b_customer index PRIMARY assign_user 5 NULL 34353 Using where; Using index
然后用load data 导入A表数据量大的时候 load的速度是普通insert 的20倍
如果a表是myisam表,试试这样:
alter table a disable keys;
你的插入语句
alter table a enable keys;如果a表是Innodb表,试试这样:
方法1:这个引擎的表是按照主键顺序存放的,所以将导入的数据按照主键顺序排好后插入会快点;
方法2:可以尝试禁用唯一约束
set unique_checks=0;
你的插入语句
set unique_checks=1;
方法3:改变 set autocommit的值
插入前 使用 set autocommit=0;语句改变事务提交模式
插入完毕后 改回来 set autocommit = 1;
方法4:用load data比insert快很多
先导出,再导入,这样比一个个INSERT要快很多。