當前位置:首頁 » 操作系統 » 資料庫優化notin

資料庫優化notin

發布時間: 2023-06-05 08:04:25

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

熱點內容
java返回this 發布:2025-10-20 08:28:16 瀏覽:645
製作腳本網站 發布:2025-10-20 08:17:34 瀏覽:936
python中的init方法 發布:2025-10-20 08:17:33 瀏覽:632
圖案密碼什麼意思 發布:2025-10-20 08:16:56 瀏覽:821
怎麼清理微信視頻緩存 發布:2025-10-20 08:12:37 瀏覽:731
c語言編譯器怎麼看執行過程 發布:2025-10-20 08:00:32 瀏覽:1066
郵箱如何填寫發信伺服器 發布:2025-10-20 07:45:27 瀏覽:299
shell腳本入門案例 發布:2025-10-20 07:44:45 瀏覽:160
怎麼上傳照片瀏覽上傳 發布:2025-10-20 07:44:03 瀏覽:851
python股票數據獲取 發布:2025-10-20 07:39:44 瀏覽:763