数据库优化技巧之in和not in

时间:2014-06-22 16:36:50   收藏:0   阅读:244

在编写SQL语句时,如果要实现一张表有而另外一张表没有的数据时, 通常第一直觉的写法是:

select * from table1 where table1.id not in(select id from table2)

这种写法虽然看起来很直观,但是执行的效率会非常低下,在数据量很大的时候效果尤其明显,我们推荐使用not exists或左连接来代替。

select a.* from table1 a left join table2 b on a.id=b.id where b.id is null

同样,这种方法也适用于in

数据库优化技巧之in和not in,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!