当我运行以下sql时,mysql(版本5.7)提示
Error Code: 1055. Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'count_cabinet.cabinet_count' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
表定义:
CREATE TABLE `bundle_v2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
);
CREATE TABLE `cabinet_v2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bundle_id` int(11),
PRIMARY KEY (`id`)
);
sql:
SELECT bundle_v2.id AS bundle_id,
count_cabinet.cabinet_count AS count_cabinet_cabinet_count
FROM bundle_v2
LEFT OUTER JOIN
(
SELECT cabinet_v2.bundle_id AS bundle_id, count(cabinet_v2.id) AS cabinet_count
FROM cabinet_v2
GROUP BY cabinet_v2.bundle_id
) AS count_cabinet ON count_cabinet.bundle_id = bundle_v2.id
GROUP BY bundle_v2.id
如果我们将 cabinet_v2.bundle_id
设置为 NOT NUL
或将 LEFT OUTER JOIN
更改为 JOIN
,则一切工作正常。但不幸的是我们不能这样做。
我知道mysql关于group_by
的新规则,即选择列表中的列对于group_by
中的值应该是唯一的。但我无法弄清楚 cabinet_count
相对于 bundle_v2.id
不唯一的情况。有人可以解释一下吗?
顺便说一句:这个sql是一个大sql的一部分,我们这里必须使用子查询。所以删除子查询对我们来说不起作用。
fiddler :https://www.db-fiddle.com/f/qJqgLnU6NtPrRBUWQNqr8L/0
最佳答案
外部查询中的GROUP BY bundle_v2.id
在这里没有意义,这不是可空列的问题。
内部查询将为每个 bundle_id
返回一行,因为它将它们分组在一起并为您提供 cabinet_v2.id
计数。
因此您可以在没有GROUP BY bundle_v2.id
的情况下运行查询
SELECT bundle_v2.id AS bundle_id,
count_cabinet.cabinet_count AS count_cabinet_cabinet_count
FROM bundle_v2
LEFT OUTER JOIN
(
SELECT cabinet_v2.bundle_id AS bundle_id, count(cabinet_v2.id) AS cabinet_count
FROM cabinet_v2
GROUP BY cabinet_v2.bundle_id
) AS count_cabinet ON count_cabinet.bundle_id = bundle_v2.id
无论出于何种原因,如果您无法从查询中删除 GROUP BY bundle_v2.id
,您可以对 count_cabinet.cabinet_count< 使用
max
函数
SELECT bundle_v2.id AS bundle_id,
MAX(count_cabinet.cabinet_count) AS count_cabinet_cabinet_count
FROM bundle_v2
LEFT OUTER JOIN
(
SELECT cabinet_v2.bundle_id AS bundle_id, count(cabinet_v2.id) AS cabinet_count
FROM cabinet_v2
GROUP BY cabinet_v2.bundle_id
) AS count_cabinet ON count_cabinet.bundle_id = bundle_v2.id
GROUP BY bundle_v2.id
编辑
Query Error: Error: ER_WRONG_FIELD_WITH_GROUP: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'count_cabinet.cabinet_count' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
该错误清楚地表明您没有对 count_cabinet.cabinet_count
列使用任何聚合函数,因为它不在 group by
列表中。
在这里您可以根据您的要求做一些事情:-
- 在
count_cabinet.cabinet_count
上使用聚合函数。 - 将其与
group by
子句一起使用,例如GROUP BY bundle_v2.id, count_cabinet.cabinet_count
- 您可以利用 MySQL 的
group by
扩展功能,例如SET sql_mode = '';
,然后运行查询。
注意:第 3 步可能会给您带来意想不到的结果。
这些不是解决方法。这些是 group by
的硬性规则。您需要遵循它,否则您将面临已经遇到的错误。
关于mysql - 当在可为空列上外部连接子查询时,为什么 mysql 提示选择列表包含非聚合列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56680547/