mysql 索引 子部分_关于sql中有分组子查询时外层表的索引使用问题

查询1

explain select * from t1 where mobile in (select mobile from t2 group by mobile, draw_date );

+----+-------------+-------+-------+---------------+--------+---------+------+------+--------------------------------------+

| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |

+----+-------------+-------+-------+---------------+--------+---------+------+------+--------------------------------------+

| 1 | SIMPLE | t2 | index | NULL | mobile | 27 | NULL | 15 | Using index; Start temporary |

| 1 | SIMPLE | t1 | ref | mobile | mobile | 63 | func | 1 | Using index condition; End temporary |

+----+-------------+-------+-------+---------------+--------+---------+------+------+--------------------------------------+

此时外层表t1可以用到索引

查询2

explain select * from t1 where mobile in (select mobile from t2 group by mobile, draw_date having count(*)>1);

+----+--------------------+-------+-------+---------------+--------+---------+------+------+-------------+

| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |

+----+--------------------+-------+-------+---------------+--------+---------+------+------+-------------+

| 1 | PRIMARY | t1 | ALL | NULL | NULL | NULL | NULL | 11 | Using where |

| 2 | DEPENDENT SUBQUERY | t2 | index | mobile | mobile | 27 | NULL | 15 | Using index |

+----+--------------------+-------+-------+---------------+--------+---------+------+------+-------------+

子查询增加了having count(*)>1 外层表t1就用不上索引了。

查询3

explain select * from t1 where mobile in (select mobile from (select mobile from t2 group by mobile, draw_date having count(*)>1) a);

+----+-------------+------------+-------+---------------+--------+---------+------+------+--------------------------------------+

| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |

+----+-------------+------------+-------+---------------+--------+---------+------+------+--------------------------------------+

| 1 | PRIMARY | | ALL | NULL | NULL | NULL | NULL | 15 | Start temporary |

| 1 | PRIMARY | t1 | ref | mobile | mobile | 63 | func | 1 | Using index condition; End temporary |

| 3 | DERIVED | t2 | index | mobile | mobile | 27 | NULL | 15 | Using index |

+----+-------------+------------+-------+---------------+--------+---------+------+------+--------------------------------------+

子查询再包了一层 外层表t1又可以用索引了。

怎么外层表一会能用上索引, 一会儿又不能? 何解?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值