IN 和 NOT IN
在SQL查询中,有时候我们要抽取不在另一张表或者在另外一种表中的数据,有时会使用到或者想到关键字IN 和 NOT IN。例如下面的sql语句:
select car_id from caridincarport where car_id not in (select car_id from caridinccomment);
该语句可以选择出在caridincarport而不在caridinccomment表中的car_id记录。对于数据量较小的情况下,这种选择是没有问题的,但对于数据量大的情况下,这种操作的效率确是很低的,原因是IN 和 NOT IN并不是针对索引的。
我的这两张表都有1000多条数据,使用not in的执行时间如下图。
改法
第一种方式是使用EXISTS或NOT EXISTS。针对上面的SQL语句,可以改为:
select car_id from caridincarport where not EXISTS (select car_id from caridinccomment where caridincarport.car_id =caridinccomment.car_id);
其操作时间为:
可以看出,相比于NOT IN执行效率更快了。
另外一种改法是使用JOIN的方式,针对上述SQL语句改法为:
select caridincarport.car_id from caridincarport LEFT JOIN caridinccomment ON caridinccomment.car_id = caridincarport.car_id where caridinccomment.car_id IS NULL
运行速度如下: