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;