表數據如下:要求查詢五分鐘之內在同一個controller_id相同的imsi個數超過五個的記錄
一、使用having聚合的方式
SELECT count(id) as num,imsi,controller_id from sys_client where regdate>'2019-03-12 16:02:22' GROUP BY imsi,controller_id HAVING num>1;
having聚合的使用:
1、having通常用在聚合函數前面,對聚合函數進行過濾,(MAX、MIN、COUNT、SUM)
2、having通常和group by 一起連用,因爲where不能加在group by的後面
where 和 having 的區別?
1. where 在分組之前進行限定,如果不滿足條件,則不參與分組。having在分組之後進行限定,如果不滿足結果,則不會被查詢出來
2. where 後不可以跟聚合函數,having可以進行聚合函數的判斷。
mysql語句的執行順序
select ,from, where, group by, having, order by
二、用臨時表的方式
select imsi,controller_id from (select count(id) as num from sys_client group by imsi,controller_id ) as new where new.num