mysql 分组查询并过滤
表数据如下:要求查询五分钟之内在同一个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 的区别?
- where 在分组之前进行限定,如果不满足条件,则不参与分组。having在分组之后进行限定,如果不满足结果,则不会被查询出来
- 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
还没有评论,来说两句吧...