[英]SQL MAX Function Behavior without Group By
Consider the following table:考虑下表:
CREATE TABLE test (
id INT
);
INSERT INTO test (id) VALUES (1);
INSERT INTO test (id) VALUES (2);
If I run the query:如果我运行查询:
SELECT MAX(id) as MaxId FROM test WHERE id > 10;
I get a single row having a value of null for MaxId
我得到一个单行,其 MaxId 的值为
MaxId
However, if I run the following:但是,如果我运行以下命令:
SELECT MAX(id) as MaxId FROM test WHERE id > 10 GROUP BY id;
I get no rows returned.我没有返回任何行。
Since the WHERE
condition in both scenario are same, no rows are selected in either case.由于两种情况下的
WHERE
条件相同,因此在任何一种情况下都不会选择任何行。 My understanding is, the Group By in the second case has no significance as no rows are returned.我的理解是,第二种情况下的 Group By 没有任何意义,因为没有返回任何行。
Could someone clarify why I get a row with null
value in first query while no rows returned in second query?有人可以澄清为什么我在第一个查询中得到一行
null
值,而在第二个查询中没有返回行吗?
An aggregation query with no GROUP BY
always returns one row (well, unless the row is filtered out by a HAVING
clause).没有
GROUP BY
的聚合查询总是返回一行(好吧,除非该行被HAVING
子句过滤掉)。
If there are no rows in the table, or the WHERE
clause filters out all rows, then the aggregation results are one row with a NULL
value.如果表中没有行,或者
WHERE
子句过滤掉了所有行,则聚合结果为NULL
值的一行。
That is what happens in your first query.这就是您的第一个查询中发生的情况。
Your second query has a GROUP BY
.您的第二个查询有一个
GROUP BY
。 It returns one row per group.它每组返回一行。 But there are no groups, so the query returns no rows.
但是没有组,因此查询不返回任何行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.