MySQL 中关于 GROUP BY 的问题

2018-06-15  本文已影响99人  Gakki的伍记
前言:

在开发自己博客的时候,在 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

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;
参考:
上一篇 下一篇

猜你喜欢

热点阅读