mysql distinct 查询疑问
问题描述
需求
想知道最近N条记录中某一字段取值有哪几种
select * from t;+----+------+| id | a |+----+------+| 1 | aaa || 2 | aaa || 3 | bbb || 4 | bbb || 5 | ccc || 6 | ddd || 7 | ddd || 8 | foo || 9 | bar |+----+------+# 想知道最早4条记录中 a取值有哪几种 期望是aaa bbb 但实际不满足期望select distinct a from t order by id limit 4;+------+| a |+------+| aaa || bbb || ccc || ddd |+------+#必须使用这种写法select distinct a from (select a from t order by id limit 4) a;+------+| a |+------+| aaa || bbb |+------+
为什么第一种写法不行? 似乎是先将所有a的取值都查出来再截取4个,但此时没有id啊,只有a啊。Mysql又是怎样处理order by id的呢?
问题解答
回答1:这是由于sql的执行顺序来决定的.写的顺序:select ... from... where.... group by... having... order by.. limit [offset,] (rows)执行顺序:from... where...group by... having.... select ... order by... limit可以出来,limit是最后一个被执行的.看你的sql,其实是先找出所有的distinct(a),然后再limit 4(4个distinct a) .
回答2:首先Explain一下
mysql> explain select * from t order by id limit 4;+----+-------------+-------+-------+---------------+---------+---------+------+------+-------+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |+----+-------------+-------+-------+---------------+---------+---------+------+------+-------+| 1 | SIMPLE | t | index | NULL | PRIMARY | 4 | NULL | 4 | NULL |+----+-------------+-------+-------+---------------+---------+---------+------+------+-------+
然后加入distinct
mysql> explain select distinct a from t order by id limit 4;+----+-------------+-------+-------+---------------+---------+---------+------+------+-----------------+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |+----+-------------+-------+-------+---------------+---------+---------+------+------+-----------------+| 1 | SIMPLE | t | index | NULL | PRIMARY | 4 | NULL | 4 | Using temporary |+----+-------------+-------+-------+---------------+---------+---------+------+------+-----------------+1 row in set (0.00 sec)
区别是Extra : Using temporary,即distinct用临时表保存中间结果。
所以可以这样理解,执行结果是把select distinct a from t放到了临时表,然后再从临时表取出数据,做了where、 order by操作。
相关文章:
1. html5 - node静态资源服务器设置了Cache-Control,但浏览器从来不走3042. android - ionic应用打包部署了,但是连接不上服务器,就连写一个a标签链接到百度都不可以3. 老师百度网盘分享一下WampServer的包啊,我们下载几kb要下载一天的.4. 前端 - node vue webpack项目文件结构5. node.js - vue 子组件的菜单 如何与 父组件 通信?6. javascript - 请问如何在pc端网站调用微信支付的接口7. webpack - vue-cli写的项目(本地跑没有问题),准备放到Nginx服务器上,有什么配置需要改的?还有怎么部署?8. 微信内网页上传图片问题9. javascript - 百度的webuploader上传的问题10. javascript - echart+百度地图
