MySQL聚合函数问题

时间:2011-09-04 05:32:52

标签: mysql aggregate-functions

在以下示例中,为什么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)

1 个答案:

答案 0 :(得分:7)

HAVING子句用于过滤行组。您引用min(a)max(a)(在没有任何GROUP BY子句的情况下)聚合表中的所有a值,然后使用针对单个{{1}的比较价值。

那MySQL应该使用哪个a值?我所知道的所有其他RDBMS都会在此时抛出错误,但MySQL确实允许这样做。 From the docs

  

标准SQL不允许a子句命名任何列   在HAVING子句中找不到,除非它包含在聚合中   功能。 MySQL允许使用这些列来简化   计算。此扩展假定非组合列将   具有相同的群体价值观。 否则,结果是   不确定的。

因此,根据您获得的结果显示,最终使用GROUP BY作为1的标量值,但这种行为无法保证,同样可以使用{{ 1}}或任何其他现有a值。