group by 用于分組,結(jié)果和distinct一樣。比如 select id,name時(shí) id ---> name ,為1對(duì)多,就可以以name為行進(jìn)行分組,但是這樣也沒(méi)什么叼用,因?yàn)?/p>
select id,name from student group by name 報(bào)錯(cuò),因?yàn)間roup by原則是 select后沒(méi)用使用聚集函數(shù)的字段,都要出現(xiàn)在group by后面,成了這樣
select id,name from student group by name,id(順序 可以和select 后的字段一致),這樣寫沒(méi)用,這種體現(xiàn)和distinct一樣。
group by例子:
查找出id,name 中 id不重復(fù),name重復(fù)的表中的 ,每個(gè)name只查出一條數(shù)據(jù)。
select id,name from student where id in (select max(id) from student group by name);
理解了這句sql,基本就理解了 group by。
下面來(lái)說(shuō)說(shuō)having, 一句話,having 和 where 一樣,就是加 查詢條件的,只是 where一般放 from 后,而 having放 group by 后,
比如 select name from student
group by name
having count(name) >1; 查找出 有 name 重復(fù)的數(shù)據(jù)
新聞熱點(diǎn)
疑難解答
圖片精選