mysql的exists与inner join 和 not exists与 left join 性能差别惊人

由于客户数据量越来越大,在实践中让我发现mysql的exists与inner join 和 not exists与 left join 性能差别惊人。

我们一般在做数据插入时,想插入不重复的数据,或者盘点数据在一个表,另一个表否有存在相同的数据会用not exists和exists,例如:

insert into t1(a1) select b1 from t2 where not exists(select 1 from t1 where t1.id = t2.r_id);

 

如果t1的数据量很大时,性能会非常慢。经过实践,用以下方法能提高很多。

insert into t1(a1)
select b1 from t2
left join (select distinct t1.id from t1 ) t1 on t1.id = t2.r_id 
where t1.id is null;

 

 

select * from t1 where exists(select 1 from t2 where t1.id=t2.r_id);

 替换为:

select t1.* from t1 
inner join (select distinct r_id from t2) t2 on t1.id= t2.r_id 

 

这是实践的得出的结果。不知否有其他更好的方法,或则这个只是特例而已。 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值