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

假设有如下表:

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值