简体   繁体   English

MySQL聚合函数问题

[英]MySQL aggregate function problem

In the following example, why does the min() query return results, but the max() query does not? 在下面的示例中,为什么min()查询返回结果,但max()查询不返回结果?

mysql> create table t(id int, a int);
Query OK, 0 rows affected (0.10 sec)

mysql> insert into t(id, a) values(1, 1);
Query OK, 1 row affected (0.03 sec)

mysql> insert into t(id, a) values(1, 2);
Query OK, 1 row affected (0.02 sec)

mysql> select * from t
    -> ;
+------+------+
| id   | a    |
+------+------+
|    1 |    1 |
|    1 |    2 |
+------+------+
2 rows in set (0.00 sec)

mysql> select * from t where a < 4;
+------+------+
| id   | a    |
+------+------+
|    1 |    1 |
|    1 |    2 |
+------+------+
2 rows in set (0.00 sec)

mysql> select * from t where a < 4 having a = max(a);
Empty set (0.00 sec)

mysql> select * from t where a < 4 having a = min(a);
+------+------+
| id   | a    |
+------+------+
|    1 |    1 |
+------+------+
1 row in set (0.00 sec)

The HAVING clause is used to filter groups of rows. HAVING子句用于过滤行组。 You reference min(a) and max(a) which (in the absence of any GROUP BY clause) aggregate over all a values in the table but then use a comparison against a single a value. 您引用min(a)max(a)其(在不存在任何的GROUP BY子句)聚合在所有a表中的值,但是然后使用针对单一的比较a值。

So which a value is MySQL supposed to use? 因此,这a值的MySQL应该使用? All other RDBMSs that I know of would throw an error at this point however MySQL does allow this. 我所知道的所有其他RDBMS都会在此时抛出错误,但MySQL确实允许这样做。 From the docs 来自文档

Standard SQL does not permit the HAVING clause to name any column not found in the GROUP BY clause unless it is enclosed in an aggregate function. 标准SQL不允许HAVING子句命名GROUP BY子句中找不到的任何列,除非它包含在聚合函数中。 MySQL permits the use of such columns to simplify calculations. MySQL允许使用这些列来简化计算。 This extension assumes that the nongrouped columns will have the same group-wise values. 此扩展假定非组合列具有相同的分组值。 Otherwise, the result is indeterminate. 否则,结果是不确定的。

So in your case from the results you are getting it appears that it ended up using 1 as the scalar value for a but this behaviour is not guaranteed and it could equally well have used 2 or any other existing a value. 所以你的情况从结果你得到看来,它结束了使用1作为标量值a但这种行为并不能完全保证其可以等效地使用2或任何其他现有的a值。

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

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