简体   繁体   English

这个 SQL 查询与 HAVING 子句中的 MIN() 究竟做了什么?

[英]What does this SQL query with MIN() in HAVING clause do exactly?

I'm using MySQL and I have the following table employees : table .我正在使用 MySQL 并且我有以下表员工

I had an exercise in which I had to select the oldest person.我有一个练习,我必须 select 最年长的人。 I know the correct way to do that is with a subquery: SELECT name, dob FROM employees WHERE dob = (SELECT MIN(dob) FROM employees) .我知道正确的方法是使用子查询: SELECT name, dob FROM employees WHERE dob = (SELECT MIN(dob) FROM employees)

However, I did it like so: SELECT name, dob FROM employees HAVING dob = MIN(dob) .但是,我是这样做的: SELECT name, dob FROM employees HAVING dob = MIN(dob) Now this returns an empty set, but doesn't throw any errors.现在这将返回一个空集,但不会引发任何错误。 So what does it do exactly?那么它具体是做什么的呢? I've read that MySQL allows to refer to columns from SELECT clause in HAVING clause, without any GROUP BY clause.我读过 MySQL 允许在 HAVING 子句中引用 SELECT 子句中的列,而无需任何 GROUP BY 子句。 But why does it return an empty set?但为什么它返回一个空集?

When you use MAX (or other aggregate functions) in the select columns or the having clause, you cause an implicit GROUP BY () (that is, all rows are grouped together into a single result row).当您在 select 列或 have 子句中使用 MAX(或其他聚合函数)时,会导致隐式GROUP BY () (即,所有行都组合到一个结果行中)。

And when grouping (whether all rows or with a specific GROUP BY ), if you specify a column outside of an aggregate function (such as your dob = ) that is not one of the things being aggregated on or something functionally dependent on it (for example, some other column in a table when you are grouping by the primary key for that table), one of two things will happen:并且在分组时(无论是所有行还是使用特定的GROUP BY ),如果您在聚合 function (例如您的dob = )之外指定一列,这不是聚合的事物之一或在功能上依赖于它的事物(对于例如,当您按该表的主键分组时,表中的某些其他列),将发生以下两种情况之一:

If you have enabled the ONLY_FULL_GROUP_BY sql_mode (which is the default in newer versions), you will receive an error:如果您启用了 ONLY_FULL_GROUP_BY sql_mode(这是较新版本中的默认设置),您将收到错误消息:

In aggregated query without GROUP BY, expression... contains nonaggregated column '...';在没有 GROUP BY 的聚合查询中,表达式...包含非聚合列“...”; this is incompatible with sql_mode=only_full_group_by这与 sql_mode=only_full_group_by 不兼容

If you have not enabled ONLY_FULL_GROUP_BY, a value from some arbitrary one of the grouped rows will be used.如果您没有启用 ONLY_FULL_GROUP_BY,则将使用来自任意分组行的值。 So it is possible your dob = MIN(dob) will be true (and it will definitely be true if all rows have the same dob), but you can't rely on it doing anything useful and should avoid doing this.因此,您的dob = MIN(dob)可能为真(如果所有行都具有相同的 dob,那肯定是真的),但您不能依赖它做任何有用的事情,应该避免这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM