所有select字段,都必须出现在group by中,例外:
1.该字段为主键
2.该字段包含在聚合函数中
示例一:
select id, name from employee group by name;
id为主键,符合
示例二:
select name, sum(salary) from employee group by name;
salary在聚合函数中,符合
示例三:
select name,age, sum(salary) from employee group by name;
group by字段没有包含age, age不是主键,不符合
那select * 和group by子句如何搭配使用?
把分组结果当成一个表
示例四:
select * from table1, (select id as t from table2 group by id) m where table 1.id=m.t;