1. 程式人生 > >oracle中in與exist的用法與比較

oracle中in與exist的用法與比較

最近在工作中用到oracle的in函式,但是該函式的引數個數存在上限(1000)的限制,而且涉及查詢的兩個表還在兩個不同的資料庫中,就無法使用exists函式來替代in的使用了。但還是總結一下in與exists的用法差異。

1.in適用於內表比外表資料量小的場景:select * from testA  a where a.client_id in (select * from testB)。

原因:in方法下,oracle會執行兩個for迴圈遍歷,外迴圈次數為testA的資料,內迴圈次數為testB的資料。如果testB的資料量超過testA,很明顯執行效率會降低,只有testB的資料量小於testA時,才適合選擇in方法;

2.exists適用於內表資料多於外表的場景:select * from testA a where exists (select * from testB b where a.client_id=b.client_id)。

原因:exists方法下,oracle會執行外表和內表的遍歷查詢,外迴圈次數為testA的資料,內迴圈次數也是testA的資料量大小。所以當內表資料量小於外表時,採用in,內表資料量大於外表時,採用exists,內表等於外表時,兩者效能相當。