mysql下distinct 和group by的区别

mysql下distinct 和group by的区别,第1张

这两者本质上应该没有可比性,distinct 取出唯一列,group by 是分组,但有时候在优化的时候,在没有聚合函数的时候,他们查出来的结果也一样。

一、group by

英 [ɡru:p bai]   美 [ɡrup baɪ]

[计][WIN]分组依据

拓展资料

1、This operator also serves as input to the Group By operator.

*** 作符还充当Group By *** 作符的输入。

2、Complete the following steps to create and program the Group By operator.

完成以下步骤,创建Group By *** 作符并对它进行配置。

3、With the appropriate access path, the ORDER BY or GROUP BY requirement can be met without sorting.

使用恰当的访问路径,无需排序即可满足ORDER BY或GROUP BY需求。

4、Drag it to the right of the Group By operator.

将它拖放到Group By *** 作符的右边。

二、distinct

英 [dɪˈstɪŋkt]   美 [dɪˈstɪŋkt]

adj.明显的,清楚的卓越的,不寻常的有区别的确切的

拓展资料

1、I have distinct memories of him in his last years.

我清楚地记得他最后几年的情况。

2、Another Cup marathon between the two sides is now a distinct possibility.

双方很可能再进行一场马拉松式的优胜杯比赛。

3、The photograph showed a distinct image.

照片显出了明晰的影像。

4、I want a distinct answer to my question.

我要求对我的问题作出明确的答复。

在使用 MySQL 时,有时需要查询出某个字段不重复的记录,这时可以使用mysql提供的distinct这个关键字来过滤重复的记录,但是实际中我们往往用distinct来返回不重复字段的条数(count(distinct id)),其原因是distinct只能返回他的目标字段,而无法返回其他字段,例如有如下表user:

用distinct来返回不重复的用户名:select distinct name from user,结果为:

这样只把不重复的用户名查询出来了,但是用户的id,并没有被查询出来:select distinct name,id from user,这样的结果为:

distinct name,id 这样的mysql 会认为要过滤掉name和id两个字段都重复的记录,如果sql这样写:select id,distinct name from user,这样mysql会报错,因为distinct必须放在要查询字段的开头。

所以一般distinct用来查询不重复记录的条数。

如果要查询不重复的记录,有时候可以用group by :

select id,name from user group by name


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/6133120.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-15
下一篇 2023-03-15

发表评论

登录后才能评论

评论列表(0条)

保存