MySQL聚合函数问题

编程入门 行业动态 更新时间:2024-10-11 19:16:40
本文介绍了MySQL聚合函数问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在下面的示例中,为什么min()查询返回结果,但max()查询没有返回结果?

In the following example, why does the min() query return results, but the max() query does not?

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)

推荐答案

HAVING子句用于过滤行组.您引用min(a)和max(a)(在没有任何GROUP BY子句的情况下)它们汇总表中的所有a值,但随后将其与单个a值进行比较.

The HAVING clause is used to filter groups of rows. 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.

那么MySQL应该使用哪个a值?我知道的所有其他RDBMS都会在此时抛出错误,但是MySQL确实允许这样做. 来自文档

So which a value is MySQL supposed to use? All other RDBMSs that I know of would throw an error at this point however MySQL does allow this. From the docs

标准SQL不允许HAVING子句命名任何列 在GROUP BY子句中找不到,除非将其包含在汇总中 功能. MySQL允许使用此类列来简化 计算.此扩展假定未分组的列将 具有相同的分组值. 否则,结果是 不确定.

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. MySQL permits the use of such columns to simplify calculations. This extension assumes that the nongrouped columns will have the same group-wise values. Otherwise, the result is indeterminate.

因此,根据您的结果,您似乎会发现它最终使用1作为a的标量值,但是不能保证此行为,并且同样可以使用2或其他任何方法现有的a值.

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.

更多推荐

MySQL聚合函数问题

本文发布于:2023-11-22 01:34:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615461.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!