mysql - 讨论一个sql执行效率的问题
巴扎黑
巴扎黑 2017-04-17 11:18:17
[MySQL讨论组]

数据库版本: mysql 5.0

表结构:

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没走.

很想知道两个表关联的sql 应该如何写最佳。

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

巴扎黑
巴扎黑

全部回复(1)
巴扎黑

http://dev.mysql.com/doc/refman/5.5/en/subquery-restrictions.html
头一条:
in 子查询会被优化为exists

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

note: 这里明显楼主给错了sql, in里应该是 select id from B...

你可以看到, 此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表过索引)

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号