zoukankan      html  css  js  c++  java
  • ORDER BY clause is not in GROUP BY clause and contains nonaggregated column group-by-handling mysql group by 解决办法

    ORDER BY clause is not in GROUP BY clause and contains nonaggregated column

    1.原因

    5.7以后mysql默认开启了only_full_group_by

    https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

    SQL-92 and earlier does not permit queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are not named in the GROUP BY clause. For example, this query is illegal in standard SQL-92 because the nonaggregated name column in the select list does not appear in the GROUP BY:

    SQL-92和更早版本不允许select列表、HAVING条件或ORDER BY列表引用GROUP BY子句中未命名的非聚合列的查询。例如,这个查询在标准SQL-92中是非法的,因为select列表中的非聚合名列不会出现在GROUP BY中

    SELECT o.custid, c.name, MAX(o.payment)
      FROM orders AS o, customers AS c
      WHERE o.custid = c.custid
      GROUP BY o.custid;
    

    要使查询在SQL-92中合法,必须从select列表中删除name列,或者在GROUP BY子句中删除named列。

    2.解决办法

    2.1 修改数据库模式

    参考链接

    (修改数据库模式)[https://blog.csdn.net/HaHa_Sir/article/details/80503601]

    2.2 使用any_value(colunn)

    使用any_value(colunn) 来处理报错的列

    select id,name,any(value) from a left join b on a.id = b.a_id left join..... left join..... group by......

    2.3 改写SQL,或在程序代码中取相关列

    《高性能MySQL》中说道
    在分组查询的SELECT中直接使用非分组列通常都不是什么好主意,因为这样的结果通常是不定的,当索引改变,或者优化器选择不同的优化策略时都可能导致结果不一样。我们碰到的大多数这种查询最后都导致了故障(因为MySQL不会对这类查询返回错误),而且这种写法大部分是由于偷懒而不是为优化而故意这么设计的。建议始终使用含义明确的语法。事实上,我们建议将MySQL的SQL_MODE设置为包含ONLY_FULL_GROUP_BY,这时MySQL会对这类查询直接返回一个错误,提醒你需要重写这个查询。

  • 相关阅读:
    【游戏开发】Excel表格批量转换成CSV的小工具
    iOS
    iOS
    Xcode
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
  • 原文地址:https://www.cnblogs.com/bigorang/p/11684338.html
Copyright © 2011-2022 走看看