in與exist , not in與not exist 的區別
in和exists
in 是把外表和內表作hash 連線,而exists是對外表作loop迴圈,每次loop迴圈再對內表進行查詢。一直以來認為exists比in效率高的說法是不準確的。
如果查詢的兩個表大小相當,那麼用in和exists差別不大。
如果兩個表中一個較小,一個是大表,則子查詢表大的用exists,子查詢表小的用in:
例如:表A(小表),表B(大表)1:select * from A where cc in (select cc from B)
效率低,用到了A表上cc列的索引;select * from A where exists(select cc from B where cc=A.cc)
效率高,用到了B表上cc列的索引。
相反的2:select * from B where cc in (select cc from A)
效率高,用到了B表上cc列的索引;select * from B where exists(select cc from A where cc=B.cc)
效率低,用到了A表上cc列的索引。
not in 和not exists
如果查詢語句使用了not in 那麼內外表都進行全表掃描,沒有用到索引;而not extsts 的子查詢依然能用到表上的索引。所以無論那個表大,用not exists都比not in要快。
not in 邏輯上不完全等同於not exists,如果你誤用了not in,小心你的程式存在致命的BUG:
請看下面的例子:
create table t1 (c1 number,c2 number);
create table t2 (c1 number,c2 number);
insert into t1 values (1,2);
insert into t1 values (1,3);
insert into t2 values (1,2);
insert into t2 values (1,null);
select * from t1 where c2 not in (select c2 from t2);
no rows found
select * from t1 where not exists (select 1 from t2 where t1.c2=t2.c2);
c1 c2
1 3
正如所看到的,not in 出現了不期望的結果集,存在邏輯錯誤。如果看一下上述兩個select語句的執行計劃,也會不同。後者使用了hash_aj。
因此,請儘量不要使用not in(它會呼叫子查詢),而儘量使用not exists(它會呼叫關聯子查詢)。如果子查詢中返回的任意一條記錄含有空值,則查詢將不返回任何記錄,正如
上面例子所示:
除非子查詢欄位有非空限制,這時可以使用not in ,並且也可以通過提示讓它使用hasg_aj或merge_aj連線。
相關文章
- 關於 in與exist , not in與not exist 的區別
- SQL語句中not in 和not exist的區別SQL
- Oracle in and existOracle
- oracle exists and not existOracle
- SQL not exist out joinSQL
- jquery judge element existjQuery
- asmcmd does not exist in directoryASM
- javax.media does not existJava
- 'mysql.column_stats' doesn't exist and Table 'mysql.index_stats' doesn't existMySqlIndex
- sql case when, Exist ,group by ,聚合SQL
- Property [title] does not exist on this collection instance
- Waring: /dev/centos/swap does not existdevCentOS
- PatchObject constructor:Input file does not existObjectStruct
- &與&&, |與||區別
- Oracle集合的first, last , next ,count,existOracleAST
- ??與?:的區別
- PSQLexception: ERROR : type "signed" does not existSQLExceptionError
- Laravel Class env does not exist 問題排查Laravel
- SNMP TABLE ERROR : Requested table is empty or does not existError
- ORA-00942: table or view does not existView
- which situation IN is better than exist, and vice versa.
- FAQ:Field DATABASE does not exist; see long textDatabase
- Oracle not exist子查詢全掃的優化Oracle優化
- MySQL的@與@@區別MySql
- mybatis #與$的區別MyBatis
- Null 與 “” 的區別Null
- PHPCookie與Session的使用與區別PHPCookieSession
- relation with OID 637165 does not exist
- SQLite中中實現 if not exist 類似功能SQLite
- MYSQL ERROR 1146 Table doesnt exist 解析MySqlError
- about Res folder doesn't exist in android projectAndroidProject
- cookie與session的區別與聯絡CookieSession
- Session與Cookie的區別與聯絡SessionCookie
- 同步與阻塞的區別與聯絡
- 詳解not in與not exists的區別與用法
- memcache與memcached的區別與安裝
- hive與hbase的聯絡與區別Hive
- JDBC與ODBC的區別與應用JDBC