数据库优化notin
❶ sql优化 - 避免使用 IN 和 NOT IN
1、效率低
2、容易出现问题,或查询结果有误 (不能更严重的缺点)
1、用 EXISTS 或 NOT EXISTS 代替
select * from test1
where EXISTS (select * from test2 where id2 = id1 )
select * FROM test1
where NOT EXISTS (select * from test2 where id2 = id1 )
2、用JOIN 代替
select id1 from test1
INNER JOIN test2 ON id2 = id1
select id1 from test1
LEFT JOIN test2 ON id2 = id1
where id2 IS NULL
妥妥的没有问题了!
PS:那我们死活都不能用 IN 和 NOT IN 了么?并没有,一位大神曾经说过,如果是确定且有限的集合时,可以使用。如 IN (0,1,2)。
❷ 求优化一句sql语句,not in速度太慢了
有俩种方法可以提高查询效率, 1、 用not exists 代替 not in , 这种发法没有改变查询数据的形式,所以可能效果不明显。 2、 利用索引查询, select tbl1.id from table1 tbl1 left join table2 tbl2 on tbl1.id = tbl2.id where tbl2.id = null; 这个是把table2表过滤,查询直接找索引。