SQL优化 - 避免使用 IN 和 NOT IN

2020-09-06  本文已影响0人  弓长_88c0

WHY?(https://blog.csdn.net/fly910905/article/details/78288685)

1、效率低

2、容易出现问题,或查询结果有误 (不能更严重的缺点)

insert into test2 (id2) values (NULL)
  1. (跑题一句:建表的时候最好不要允许含空值,否则问题多多。)

HOW?

1、用 EXISTS 或 NOT EXISTS 代替

select * from test1where EXISTS (select * from test2 where id2 = id1 )select * FROM test1where NOT EXISTS (select * from test2 where id2 = id1 )

2、用JOIN 代替

select id1 from test1INNER JOIN test2 ON id2 = id1select id1 from test1LEFT JOIN test2 ON id2 = id1where id2 IS NULL

妥妥的没有问题了!

综合以上对IN/EXISTS的讨论,我们可以得出一个基本通用的结论:IN适合于外表大而内表小的情况;EXISTS适合于外表小而内表大的情况。

上一篇 下一篇

猜你喜欢

热点阅读