`
openxtiger
  • 浏览: 147388 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

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 

 

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

 

3
3
分享到:
评论
1 楼 zhouweideshijie 2017-02-24  
为什么在join的时候需要(select distinct t1.id from t1 ),这样做的好处是什么

相关推荐

Global site tag (gtag.js) - Google Analytics