當前位置:首頁 » 操作系統 » 資料庫優化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表過濾,查詢直接找索引。

熱點內容
scratch少兒編程課程 發布:2025-04-16 17:11:44 瀏覽:627
榮耀x10從哪裡設置密碼 發布:2025-04-16 17:11:43 瀏覽:356
java從入門到精通視頻 發布:2025-04-16 17:11:43 瀏覽:73
php微信介面教程 發布:2025-04-16 17:07:30 瀏覽:297
android實現陰影 發布:2025-04-16 16:50:08 瀏覽:787
粉筆直播課緩存 發布:2025-04-16 16:31:21 瀏覽:337
機頂盒都有什麼配置 發布:2025-04-16 16:24:37 瀏覽:202
編寫手游反編譯都需要學習什麼 發布:2025-04-16 16:19:36 瀏覽:800
proteus編譯文件位置 發布:2025-04-16 16:18:44 瀏覽:356
土壓縮的本質 發布:2025-04-16 16:13:21 瀏覽:582