Sqlalchemy中mysql分组groupby用法 this is incompatible with sql_mode=only_full_group_by解决方法
MySQL 5.7.5后only_full_group_by成为sql_mode的默认选项之一,这可能导致一些sql语句失效。
解决方法
1. 把group by字段group_id设成primary key 或者 unique NOT NULL。这个方法在实际操作中没什么意义。
2. 使用函数any_value把报错的字段name包含起来。如,select any_value(name), group_id from game group by group_id。
3. 在配置文件my.cnf中关闭sql_mode=ONLY_FULL_GROUP_BY。
msqyl的默认配置是sql_mode=ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION。可以把ONLY_FULL_GROUP_BY去掉,也可以去掉所有选项设置成sql_mode=,如果你确信其他选项不会造成影响的话。
在SQLAlchemy中func.any_value函数也是可以实现的,该函数最后也是转成了mysql中的any_value函数
sql = db.session.query(func.any_value(Article.category_id),func.any_value(func.count(Article.id)) ).group_by(func.date_format(Article.create_time, "%Y-%m-%d"))
对应的sql
SELECT any_value(article.category_id) AS any_value_1, any_value(count(article.id)) AS any_value_2
FROM article GROUP BY date_format(article.create_time, %(date_format_1)s)