项目部署后报错
SequelizeDatabaseError: ER_WRONG_FIELD_WITH_GROUP: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘mysql.category.id’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
简单来说就是:输出的结果是叫target list,就是select后面跟着的字段,还有一个地方group by column,就是group by后面跟着的字段。由于开启了ONLY_FULL_GROUP_BY的设置,所以如果一个字段没有在target list 和group by字段中同时出现,或者是聚合函数的值的话,那么这条sql查询是被mysql认为非法的,会报错误。
报错出处代码:
// 查询全部
const categoryAll = async (ctx) => {
const resData = await Category.findAll({
attributes: ['name', 'id', [sequelize.fn('COUNT', sequelize.col('name')), 'count']],
// group: 'name', // 关键行
where: {
articleId: { [Op.not]: null }
},
order: [[sequelize.fn('COUNT', sequelize.col('name')), 'desc']]
})
ctx.body = successResult(resData)
}
解决方法:
几篇参考文章中都提到了全局修改sql_mode,不过我用了这种方法并没有修改成功,即使成功了也是暂时性的,在mysql重启后又会重现。
所以我选择了另一种方法,修改mysql配置文件,通过手动添加sql_mode的方式强制指定不需要ONLY_FULL_GROUP_BY属性。
1、确认mysql加载的是哪个配置文件那你可以使用以下方法进行确认
mysql --verbose --help | grep my.cnf
我的配置所在目录:
2、修改配置,配置文件结尾添加以下内容
[mysqld]
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
注意:我的配置文件没有关键字[mysqld],没有关键字会报错。
然后重启mysql就可以了。
参考文章:
1、mysql出现Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggre错误
2、How to disable only_full_group_by in MySQL or Sequelize
3、MySql版本问题sql_mode=only_full_group_by的完美解决方案
4、"this is incompatible with sql_mode=only_full_group_by"错误解决方案