-
当查询数据较大时,尤其是使用in和not in的时候会极大降低查询效率,所以需要进行优化,我们一般采用join 的进行优化。(记住是in中数据量较大才进行优化,如果in中数据量很少,请不要修改)。
-
第一种 in:
-
select * from tb1 where id in(select id_new from tb2);
-
优化: select * from tb1 inner join (select id_new from tb2) as tb2 on tb1.id=tb2.id_new;
-
select * from tb1 where id in(select distinct id_new from tb2);
-
select * from tb1 inner join (select distinct id_new from tb2) as tb2 on tb1.id=tb2.id_new;
-
第二种not in: 首先尽量避免使用not in。而且not in 是直接排除值为null的情况,会发现比实际值要少。
-
select * from tb1 where id not in(select id_new from tb2);
-
select * from tb1 left join (select id_new from tb2) as tb2 on tb1.id=tb2.id_new where tb2.id_new is null;
SQL中in和not in优化--join
最新推荐文章于 2024-04-21 14:13:51 发布