数据库
MYSQL8.0 聚合查询未分组错误:sql_mode=only_full_group_by
  • By刘立博
  • 2021-01-27 22:11:14
  • 1145人已阅读

问题

当我们聚合查询中有未分组的字段时,MYSQL会抛出以下错误:

In aggregated query without GROUP BY …… this is incompatible with sql_mode=only_full_group_by

复现该错误

 

创建user表

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `money` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '张三', '100');
INSERT INTO `user` VALUES (2, '李四', '299');

SET FOREIGN_KEY_CHECKS = 1;

执行SQL

 

SELECT name,AVG(money) FROM user

 

此时MYSQL便会抛出异常1140

SELECT name,AVG(money) FROM user

> 1140 - In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'erp-back.user.name'; this is incompatible with sql_mode=only_full_group_by

> 时间: 0.114s

错误产生的原因

 

我们使用聚合函数AVG将money字段聚合为一行,但是并没有对name执行聚合操作。所以导致name有两行,二money只有一行,于是MYSQL认为此查询可能存在潜在问题。

 

如何解决该错误

 

使用GROUP对未聚合字段进行分组

MYSQL推荐以GROUP的此方式对未聚合字段进行分组,以达到聚合的目的

SELECT name,AVG(money) FROM user GROUP BY name

 

 

使用GROUP_CONCAT拼接未聚合字段

但使用GROUP对未聚合字段分组后,会导致结果集变为多行,有违聚合初衷。我们也可以使用GROUP_CONCAT将未聚合字段拼接为一行

 

SELECT GROUP_CONCAT(name),AVG(money) FROM user