热线电话:13121318867

登录
2019-02-18 阅读量: 721
sql执行效率的问题

问题描述:

表结构:

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数据
B表有1000条数据
select * from B where cid = 1 的结果集是(1,3,5,10) ,不管cid=*,结果集都在10以内。

对比以下三个sql的执行效率:

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)

我现在测试的情况是 SQL1 和 SQL 3 数据相当,SQL2最慢. explain 看到的SQL1和SQL3都走了索引,但是SQL2没走.

还要分别考虑以下2种情况:
1.B表也是大表,但是select * from B where cid = 1 的结果集还是(1,3,5,10)
2.B表也是大表,但是select * from B where cid = 1 的结果集很大

解决方法:

in 子查询会被优化为exists

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

此sql被优化为(手写, 未实际验证):

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

这样本来应该是 从in子查询中拿到10条数据, 去a表走索引查询, 变为:
遍历a表, 对每条记录去过exists,由 10(in子查询结果集) X 1(a表过索引), 变为: 200w(遍历a表) X 1(b表过索引)

0.0000
0
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子