GROUP BY 子句没有聚合函数有什么原因吗?
我现在正在(彻底)学习 SQL,并遇到了 GROUP BY
子句。
GROUP BY
根据您提供的参数对结果集进行聚合或分组。如果您在查询中使用此子句,则可以对结果集执行聚合函数以查找结果集的统计信息,例如查找平均值 (AVG())
或频率 (COUNT())< /代码>。
我的问题是:如果没有附带的聚合函数,GROUP BY 语句是否有用?
更新 使用 GROUP BY
作为 DISTINCT
的同义词(可能)是一个坏主意,因为我怀疑它会更慢。
I'm (thoroughly) learning SQL at the moment and came across the GROUP BY
clause.
GROUP BY
aggregates or groups the resultset according to the argument(s) you give it. If you use this clause in a query you can then perform aggregate functions on the resultset to find statistical information on the resultset like finding averages (AVG())
or frequency (COUNT())
.
My question is: is the GROUP BY statement in any way useful without an accompanying aggregate function?
Update
Using GROUP BY
as a synonym for DISTINCT
is (probably) a bad idea because I suspect it is slower.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在这种情况下,使用
DISTINCT
将是同义词,但您想要/必须定义GROUP BY
子句的原因是为了能够定义 < code>HAVING 子句详细信息。如果您需要定义
HAVING
子句,则必须定义GROUP BY
- 您不能这样做它与DISTINCT
结合使用。Using
DISTINCT
would be a synonym in such a situation, but the reason you'd want/have to define aGROUP BY
clause would be in order to be able to defineHAVING
clause details.If you need to define a
HAVING
clause, you have to define aGROUP BY
- you can't do it in conjunction withDISTINCT
.您可以使用不带任何AGGREGATES的GROUP BY来执行DISTINCT选择。
You can perform a DISTINCT select by using a GROUP BY without any AGGREGATES.
分组依据主要可以两种方式使用
1) 与 SQL 聚合函数结合
2)从结果集中消除重复行
所以您的问题的答案位于上述用途的第二部分。
Group by can used in Two way Majorly
1)in conjunction with SQL aggregation functions
2)to eliminate duplicate rows from a result set
SO answer to your question lies in second part of USEs above described.
注意:以下所有内容仅适用于
MySQL
GROUP BY
是 保证按顺序返回结果,DISTINCT
则不然。GROUP BY
与ORDER BY NULL
的效率与DISTINCT
相同(并以 say 方式实现)。如果正在聚合(或区分)的字段上有索引,则两个子句都对该字段使用松散索引扫描。在
GROUP BY
中,您可以返回非分组和非聚合表达式。MySQL
将从相应组中选取任意随机值来计算表达式。使用
GROUP BY
,您可以省略SELECT
子句中的GROUP BY
表达式。使用DISTINCT
,你就做不到。DISTINCT
返回的每一行都保证是唯一的。Note: everything below only applies to
MySQL
GROUP BY
is guaranteed to return results in order,DISTINCT
is not.GROUP BY
along withORDER BY NULL
is of same efficiency asDISTINCT
(and implemented in the say way). If there is an index on the field being aggregated (or distinctified), both clauses use loose index scan over this field.In
GROUP BY
, you can return non-grouped and non-aggregated expressions.MySQL
will pick any random values from from the corresponding group to calculate the expression.With
GROUP BY
, you can omit theGROUP BY
expressions from theSELECT
clause. WithDISTINCT
, you can't. Every row returned by aDISTINCT
is guaranteed to be unique.它不仅仅用于聚合函数。
例如,考虑以下代码:
这将仅返回每个产品 1 个结果,但包含该记录的最新更新值。
It is used for more then just aggregating functions.
For example, consider the following code:
This will return only 1 result per product, but with the latest updated value of that records.