簡單描述:需要查詢一個數量count,於是做分組查詢后,發現有的數據沒有過濾掉,於是就想加上過濾條件,就在group by后邊寫了where ,發現不好使,直接就報錯了,查了一下,where只能寫在group by前邊,要想在后邊加限制條件,應該使用having關鍵字
直接放結果:
先說一下聚合函數:
count(a):遇到每個元素 a就加1
其他的還有:
MAX(a)和MIN(a):分別記錄迄今為止見到的任意元素在屬性a上的最大值或最小值,如果遇到了,就替換掉。
sum(a):如果a不為null,則將值累加到輸出值上
AVG(a):計算出sum和count,然后相除
通常通過group by來比較where 和 having。這里說的是通常,並不是說having必須和group by連用,下面會進行說明
先來一條sql:
select sum(score) from student where gender='boy' group by name having sum(score)>210;
其次我們經常寫的sql 就是 select count(a),sum(b) ....from tableName where .... 聚合函數都是在where 條件之前的,說明聚合函數的執行級別高於where
然后where 子句的作用是在對查詢結果進行分組前,將不符合where條件的行去掉,也就是在分組之前過濾數據,條件中不能包含聚和函數,使用where條件限制特定的行。
最后having 子句的作用是篩選滿足條件的組,即在分組之后過濾數據,條件中經常包含聚合函數,使用having 條件過濾特定的組,也可以使用多個分組標准進行分組。
總之一條sql中有where having group by的時候,順序是 where group by having
where和having都可以使用的場景:
select price,name from goods where price > 100
select price,name from goods having price > 100
說明:having可用的前提是已經篩選出了price字段,在這種情況下和where的效果是等效的,But如果沒有select price 就會報錯!!因為having是從前篩選的字段再篩選,而where是從數據表中的字段直接進行的篩選的。
只可以用where,不可以用having的情況
select name from goods where price> 100
select name from goods having price> 100 //報錯!!!因為select沒有篩選出price 字段,having不能用,而where是對表進行檢索price。100
只可以用having,不可以用where情況
查詢每種id 商品價格的平均值,獲取平均價格大於100元的商品信息
select id, avg(price) as agprice from goods group by id having agprice > 100
select id, avg(price) as agprice from goods where agprice>100 group by id //報錯!!因為from goods這表里面沒有agprice這個字段
