登录
首页 >  数据库 >  MySQL

mysql distinct 使用注意事项

来源:SegmentFault

时间:2023-02-16 15:36:25 221浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《mysql distinct 使用注意事项》,聊聊MySQL,我们一起来看看吧!

想查询最近N条订单记录中订单来源(

order_from
)有哪几种,刚开始使用的SQL命令是

select distinct order_from from order order by id desc limit 1000  

发觉查询的记录很多 明显1000条外的数据也查出来了。 后面改成下面的SQL

select distinct order_from from (select order_from from order order by id desc limit 1000) 

这时就对了。

演示上述现象

select * from distinct_test;
+----+------+
| id | a    |
+----+------+
|  1 | aaa  |
|  2 | aaa  |
|  3 | bbb  |
|  4 | bbb  |
|  5 | ccc  |
|  6 | ddd  |
|  7 | ddd  |
|  8 | foo  |
|  9 | bar  |
+----+------+

select distinct a  from distinct_test order by id limit 4;
+------+
| a    |
+------+
| aaa  |
| bbb  |
| ccc  |
| ddd  |
+------+

select distinct a  from (select a from distinct_test order by id limit 4) a;
+------+
| a    |
+------+
| aaa  |
| bbb  |
+------+

另外在5.7版本Mysql中第一种写法会报错 如下所示

select version();
+-----------+
| version() |
+-----------+
| 5.7.12    |
+-----------+
select distinct a from distinct_test order by id limit 4;
ERROR 3065 (HY000): Expression #1 of ORDER BY clause is not in SELECT list, references column 'test.distinct_test.id' which is not in SELECT list; this is incompatible with DISTINCT

今天带大家了解了MySQL的相关知识,希望对你有所帮助;关于数据库的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表