99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
2019-02-18 閱讀量: 752
sql執(zhí)行效率的問題

問題描述:

表結(jié)構(gòu):

create table A(
id int(11),
bid int(11),
KEY `id` (`id`),
KEY `bid` (`bid`)
)
create table B(
id int(11),
cid int(11),
KEY `id` (`id`),
KEY `cid` (`cid`)
)

初始化:
A表有200w數(shù)據(jù)
B表有1000條數(shù)據(jù)
select * from B where cid = 1 的結(jié)果集是(1,3,5,10) ,不管cid=*,結(jié)果集都在10以內(nèi)。

對比以下三個sql的執(zhí)行效率:

SQL1:select a.* from A,B where a.bid = b.id and b.cid = 1
SQL2:select * from A where a.bid in (select * from B where cid = 1)
SQL3:select * from A where a.bid in (1,3,5,10)

我現(xiàn)在測試的情況是 SQL1 和 SQL 3 數(shù)據(jù)相當(dāng),SQL2最慢. explain 看到的SQL1和SQL3都走了索引,但是SQL2沒走.

還要分別考慮以下2種情況:
1.B表也是大表,但是select * from B where cid = 1 的結(jié)果集還是(1,3,5,10)
2.B表也是大表,但是select * from B where cid = 1 的結(jié)果集很大

解決方法:

in 子查詢會被優(yōu)化為exists

explain extended select * from A where a.bid in (select * from B where cid = 1);
show warnings;

此sql被優(yōu)化為(手寫, 未實際驗證):

select * from A where exists (select 1 from B where a.bid =b.id and cid = 1);

這樣本來應(yīng)該是 從in子查詢中拿到10條數(shù)據(jù), 去a表走索引查詢, 變?yōu)?
遍歷a表, 對每條記錄去過exists,由 10(in子查詢結(jié)果集) X 1(a表過索引), 變?yōu)? 200w(遍歷a表) X 1(b表過索引)

0.0000
0
關(guān)注作者
收藏
評論(0)

發(fā)表評論

暫無數(shù)據(jù)
推薦帖子