資料庫優化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表過濾,查詢直接找索引。