group by 用于分組,結果和distinct一樣。比如 select id,name時 id ---> name ,為1對多,就可以以name為行進行分組,但是這樣也沒什么叼用,因為
select id,name from student group by name 報錯,因為group by原則是 select后沒用使用聚集函數的字段,都要出現在group by后面,成了這樣
select id,name from student group by name,id(順序 可以和select 后的字段一致),這樣寫沒用,這種體現和distinct一樣。
group by例子:
查找出id,name 中 id不重復,name重復的表中的 ,每個name只查出一條數據。
select id,name from student where id in (select max(id) from student group by name);
理解了這句sql,基本就理解了 group by。
下面來說說having, 一句話,having 和 where 一樣,就是加 查詢條件的,只是 where一般放 from 后,而 having放 group by 后,
比如 select name from student
group by name
having count(name) >1; 查找出 有 name 重復的數據
新聞熱點
疑難解答