MySQL 中关于 GROUP BY 的问题

前言:

在开发自己博客的时候,在 Centos 中 MySQL 客户端中使用 GROUP BY 相关查询语句,发现了一个兼容错误。但在 win 版本的 MySQL 并未发现该错误。甚是不解。。。

相关 SQL 语句和错误的描述
SELECT
    t2.id,
    t2.typeName,
    COUNT( t1.id ) AS blogCount 
FROM
    t_blog t1
    RIGHT JOIN t_blogtype t2 ON t1.typeId = t2.id 
GROUP BY
    t2.typeName
ORDER BY
    t2.orderNo;

错误:
Expression #1 of SELECT list is not in GROUP BY clause and contains 
nonaggregated column 'db_blog.t2.id' which is not functionally 
dependent on columns in GROUP BY clause; this is incompatible with 
sql_mode=only_full_group_by
  • 上面的解释可为:db_blog.t2.id 在 GROUP BY 中违背了 mysql 的规则。

  • 进过自己的一番百度与 Google,有人说要改变 sql_model 的方式,但我感觉这样不好,终于解决了问题,
    发现 MySQL: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sss 这篇博客有说道:

select 字段必须都在 group by 分组条件内(含有函数的字段除外)。(如果遇到 order by 也出现这个问题,同理,order by 字段也都要在group by内 )

于是乎, GROUP BY 中加入 t2.id,成功解决问题。

SELECT
    t2.id,
    t2.typeName,
    COUNT( t1.id ) AS blogCount 
FROM
    t_blog t1
    RIGHT JOIN t_blogtype t2 ON t1.typeId = t2.id 
GROUP BY
    t2.typeName,
    t2.id 
ORDER BY
    t2.orderNo;
参考:
  • MySQL: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sss
  • SQL-GROUP BY语句在MySQL中的一个错误使用被兼容的情况
  • Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'userinfo.

你可能感兴趣的:(MySQL 中关于 GROUP BY 的问题)