查询注意事项

group by使用注意事项:

执行下面查询语句:

select username, class from user group by username;

会报错:

Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test007.user.class' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

正确解法:
select的查询子句,也就是上面的username、class,必须在group by子句里存在

where子句在group by子句前面

各种子句的执行顺序

from -> where -> group by -> select -> order by -> limit

where子句中不能有聚合函数(count、avg、sum)

having子句可加入聚合函数,它是放在group子句后

聚合查询通常跟group by一起使用

SELECT
    d.department_name,
    count(*)
FROM
    departments d
LEFT JOIN employees e ON d.department_id = e.department_id
GROUP BY
    d.department_name;
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容