研究一条distinct+order by+limit的SQL执行过程,发现limit影响排序结果的彩蛋

本文探讨了一条包含distinct、order by和limit的SQL在MySQL中的执行过程。通过实验发现,limit子句实际上会影响排序结果,尤其是在order by的列不是唯一索引时。对于某些情况,SQL的执行逻辑是从排序后的结果集中按limit要求选取不重复的记录。文章还提到了rows_examined在不同情况下可能的差异,并指出这可能与优化器对主键索引的访问方式有关。
摘要由CSDN通过智能技术生成

假设有如下表:

mysql> select * from tab;
+----+------+
| id | col1 |
+----+------+
|  1 |    2 |
|  2 |    2 |
|  3 |    5 |
|  4 |    3 |
|  5 |    3 |
|  6 |    4 |
+----+------+
6 rows in set (0.01 sec)

mysql> desc tab;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
| col1  | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

那么,下面的SQL是怎样的执行过程呢?
select distinct id from tab order by col1 desc limit 1,2;
1.先执行select distinct id from tab order by col1 desc,在筛选limit 1,2;?等效于select * from (select distinct id from tab order by col1 desc) a limit 1,2
2.先执行select * from tab order by col1 desc limit 1,2;,再选出distinct id?等效于select distinct id from (select * from tab order by col1 desc limit 1,2) a
3.先执行select * from tab order by col1 desc,再从结果集中第一行数据进行去重,直到取到3个数值,然后拿后面2个?

我们先从实际数据来验证一下:
首先,先执行一下select distinct id from tab order by col1 desc limit 1,2;,看看实际的返回结果是什么:

mysql> select distinct id from tab order by col1 desc limit 1,2;
+----+
| id |
+----+
|  6 |
|  5 |

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值