假设有如下表:
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 |