有两个表 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都是主键

解决方案 »

  1.   

    1 主键不冲突吗
    2 alter table a disable keys
    3 排序插入
      

  2.   

    不会冲突,你的SQL语句
    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表试试
      

  3.   

    现在要把 b 表里有而a 表里没有的记录,存入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;
      

  4.   

    ----left join 的
    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 
      

  5.   

    ...用语句找出符合条件的语句 导入文件 
    然后用load data 导入A表数据量大的时候 load的速度是普通insert 的20倍
      

  6.   

    再来说几点插入的优化:
    如果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快很多
      

  7.   


    先导出,再导入,这样比一个个INSERT要快很多。