gpt4 book ai didi

mysql - SQL 与 MySQL : Rules about aggregate operations and GROUP BY

转载 作者:IT王子 更新时间:2023-10-29 00:30:57 26 4
gpt4 key购买 nike

this book我目前正在阅读有关数据库的类(class),给出了以下使用聚合运算符的非法查询示例:

Find the name and age of the oldest sailor.

Consider the following attempt to answer this query:

SELECT S.sname, MAX(S.age)
FROM Sailors S

The intent is for this query to return not only the maximum age but also the name of the sailors having that age. However, this query is illegal in SQL--if the SELECT clause uses an aggregate operation, then it must use only aggregate operations unless the query contains a GROUP BY clause!

一段时间后,在使用 MySQL 进行练习时,我遇到了类似的问题,并犯了与上述类似的错误。然而,MySQL 并没有提示,只是吐出一些表,后来证明这不是我需要的。

上面的查询在 SQL 中真的是非法的,但在 MySQL 中是合法的吗?如果是,那是为什么?什么情况下需要进行这样的查询?

问题的进一步阐述:

问题不在于 SELECT 中提及的所有属性是否也应在 GROUP BY 中提及。这就是为什么上面的查询,使用属性和对属性的聚合操作,没有任何 GROUP BY 在 MySQL 中是合法的。

假设 Sailors 表看起来像这样:

+----------+------+
| sname | age |
+----------+------+
| John Doe | 30 |
| Jane Doe | 50 |
+----------+------+

查询将返回:

+----------+------------+
| sname | MAX(S.age) |
+----------+------------+
| John Doe | 50 |
+----------+------------+

现在谁需要它? John Doe 不是 50 岁,他已经 30 岁了!正如书中的引文所述,这是获取最年长水手的姓名和年龄的首次尝试,在本例中,Jane Doe 是 50 岁。

SQL 会说这个查询是非法的,但 MySQL 只是继续执行并吐出“垃圾”。谁会需要这样的结果?为什么 MySQL 会为新手设置这个小陷阱?

最佳答案

顺便说一下,这是 MySQL 的默认行为。但它可以通过在 my.ini 文件或 session 中设置 ONLY_FULL_GROUP_BY 服务器模式来更改 -

SET sql_mode = 'ONLY_FULL_GROUP_BY';
SELECT * FROM sakila.film_actor GROUP BY actor_id;

Error: 'sakila.film_actor.film_id' isn't in GROUP BY

ONLY_FULL_GROUP_BY - 不允许选择列表引用未在 GROUP BY 子句中命名的非聚合列的查询。

关于mysql - SQL 与 MySQL : Rules about aggregate operations and GROUP BY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12843303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com