我的sql语句中有GROUP BY的一些问题.
我正在使用mariaDB 10.1.17,并且注意到执行以下sql语句时出现错误:
SELECT `pubs`.`ID` AS `ID`
,AVG(`reviews`.`atmosphere`) AS `average`
,`pubs`.`name` AS `name`
,`pubs`.`country` AS `country`
FROM `pubs`
LEFT JOIN `reviews` ON `pubs`.`ID` = `reviews`.`pub_ID`
GROUP BY `pubs`.`ID`
ORDER BY `average` DESC
,`reviews`.`date` DESC
我得到的错误是
“Syntax error or access violation: 1055 ‘pubreviews.pubs.name’ isn’t
in GROUP BY”
我的理解是,由于“功能依赖性”(一个ID映射到一个名称和国家/地区),因此不需要将这些列显式添加到group by语句中.
(我只有ONLY_FULL_GROUP_BY已打开)
谢谢
解决方法:
根据mariadb文档,如果打开ONLY_FULL_GROUP_BY sql模式,则似乎不考虑功能依赖性.
关于ONLY_FULL_GROUP_BY sql模式的文档说:
For SELECT … GROUP BY queries, disallow SELECTing columns which are not referred to in the GROUP BY clause, unless they are passed to an aggregate function like COUNT() or MAX(). Produce a 1055 error.
If you select a non-grouped column or a value computed from a non-grouped column, it is undefined which row the returned value is taken from. This is not permitted if the ONLY_FULL_GROUP_BY sql_mode is used.
以上内容适用于mariadb版本10.1.18和10.2.2.