数据库 - mysql为什么用了子查询后,主查询没走主键索引
高洛峰
高洛峰 2017-04-17 11:52:20
[MySQL讨论组]

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(2)
迷茫

这是一个非常非常old的问题.

mysql 的in子查询 永远被 转为exists 查询, 具体见手册
http://dev.mysql.com/doc/refman/5.7/en/subquery-restrictions.html
第一条limitation.

演示一下:

mysql> explain extended select id from yanse where name in (select name from yan
se);
...

mysql> show warnings;
+-------+------+----------------------------------------------------------------
--------------------------------------------------------------------------------
----------------------------------------------------------------+
| Level | Code | Message

                                                                |
+-------+------+----------------------------------------------------------------
--------------------------------------------------------------------------------
----------------------------------------------------------------+
| Note  | 1003 | select `test1`.`yanse`.`id` AS `id` from `test1`.`yanse` where
<in_optimizer>(`test1`.`yanse`.`name`,<exists>(select 1 from `test1`.`yanse` whe
re (<cache>(`test1`.`yanse`.`name`) = `test1`.`yanse`.`name`))) |
+-------+------+----------------------------------------------------------------
--------------------------------------------------------------------------------
----------------------------------------------------------------+
1 row in set (0.00 sec)

in 和exists的不同:
https://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:953229842074

Select * from T1 where x in ( select y from T2 )

is typically processed as:

select * from t1, ( select distinct y from t2 ) t2 where t1.x = t2.y;

The subquery is evaluated, distinct'ed, indexed (or hashed or sorted)
and then joined to the original table -- typically.

As opposed to

select * from t1 where exists ( select null from t2 where y = x )

That is processed more like:

>    for x in ( select * from t1 )    loop
>       if ( exists ( select null from t2 where y = x.x )
>       then 
>          OUTPUT THE RECORD
>       end if    end loop
天蓬老师

你不用子查询的时候,也没有走主键索引啊。。。呵呵

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

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