測試1w條資料和100w條資料下 in 和 exists的區別:
#t_user 為100w條,t_user_memory 為1w條#1、in的原理:
#在select
*from a where id in(select id from b); 中,in
()中的子查詢只執行一次,它查詢出b表中的所有id值並快取起來;之後,在記憶體中檢查a表的id是否與b表中的id值相等,如果相等則則將a表的記錄加入到結果集中,直到遍歷完a表中的所有記錄。
#所以b表的條數多少對查詢影響很大#2
、exists的應用原理
#在select
*from a where
exists (select
from b where a.id=
b.id);之中
#exists
()會執行a.length次,它並不快取exists()結果集,因為exists()結果集的內容並不重要,重要的是其內查詢語句的結果集空或者非空,空則返回false,非空則返回true,true的時候才會去查詢,這樣從執行次數上來說是少於in#3
、 二者相比,在相同表下雖然exists執行次數普遍小於in,但是in 是在記憶體中做遍歷比較的,exists則是在資料庫中查詢,這兩個相比肯定是記憶體快一些。#4
、測試: t_user 比 t_user_memory表大,**應當用in效率更高
#t_user資料 大於 t_user_memory資料
# 加索引# 0
.98s多
select
*from t_user where
exists(select c_name from t_user_memory where c_name=
t_user.c_name);# 0
.86s左右
select
*from t_user where c_name in(select c_name from
t_user_memory);
# 當子查詢小於外層查詢時,
inexists
效率高# 約0.85s
select
*from t_user_memory where
exists(select c_name from t_user where c_name=
t_user_memory.c_name);
# 約0.87s
select
*from t_user_memory where c_name in(select c_name from
t_user);
# 當子查詢大於外層查詢時,
exists 比 in
效率高# 不加索引
#五次取均值# 2
.53s左右
select
*from t_user where
exists(select c_user_id from t_user_memory where c_user_id=
t_user.c_user_id);# 2
.02s左右
select
*from t_user where c_user_id in(select c_user_id from
t_user_memory);
# 當子查詢小於外層查詢時,
in比 exists效率高# 2
.27s左右
select
*from t_user_memory where
exists(select c_user_id from t_user where c_user_id=
t_user_memory.c_user_id);# 2
.29s左右
select
*from t_user_memory where c_user_id in(select c_user_id from
t_user);
# 當子查詢大於外層查詢時,exists比in效率高
Exists與In效率分析
a in 是把外表和內錶做hash 連線,而exists 是對外表作loop 迴圈,每次loop迴圈再對內表進行查詢。當查詢兩個表的大小相當時,用in 和 exists差別不大。如果兩個表中乙個表較小,乙個表較大,那麼子查詢表大的用exists,子查詢錶小的用in,效率會高的。也就是說in適合於外表...
mysql in 和exists查詢效率總結
看到網上好多的文章,關於in 和exists,我自己專門去校驗了一下,自己通過儲存過程,迴圈增加了10萬條資料,建立表 drop table if exists tb test create table tb test id int primary key auto increment not nu...
exists和in的查詢及效率比較
有兩個簡單例子,以說明 exists 和 in 的效率問題 sql 1 select from t1 where exists select 1 from t2 where t1.a t2.a t1資料量小而t2資料量非常大時,t1 2 select from t1 where t1.a in se...