mysql 数据操作 单表查询 having 过滤

SELECT 字段1,字段2... FROM 库名.表名
                  WHERE 条件
                  GROUP BY field
                  HAVING 筛选
                  ORDER BY field
                  LIMIT 限制条数

1.首先找到表 库.表名

2. 经过where 过滤条件 找到符合条件记录

3.按照分组归类 只剩下组这个单位

4.剩下只能取 组名和聚合函数 ,having过滤只有分组 和聚合函数

HAVING与WHERE不一样的地方在于

执行优先级从高到低:where > group by > having 
#1. Where 发生在分组group by之前,因而Where中可以有任意字段,但是where绝对不能使用聚合函数。

#2. Having发生在分组group by之后,因而Having中可以使用分组的字段无法直接取到其他字段,可以使用聚合函数

having 过滤 是在分组之后进行

having 一定配合聚合函数使用

例如:

报错

分组后无法取到其他字段

因为 id_info 是别名,是运行在having之后的 distinct 字段   在执行 having id_info   id_info就不存在, id_info在后面执行 所以这里报错

mysql> select post,count(id) as id_info from employee group by post having id_info >5;
ERROR 1463 (42000): Non-grouping field 'id_info' is used in HAVING clause
mysql> select * from employee having id > 5  ;
ERROR 1463 (42000): Non-grouping field 'id' is used in HAVING clause

正确使用

mysql> select post,count(id)  from employee group by post ;
+-----------+-----------+
| post      | count(id) |
+-----------+-----------+
| operation |         5 |
| sale      |         5 |
| teacher   |         6 |
+-----------+-----------+
3 rows in set (0.00 sec)

mysql> select post,count(id)  from employee group by post having count(id) >5 ;
+---------+-----------+
| post    | count(id) |
+---------+-----------+
| teacher |         6 |
+---------+-----------+
1 row in set (0.00 sec)

取 职位名以及每个职位里的员工数 并且把每个职位 里 员工数 大于5 的 职位 取出来

mysql> select post,group_concat(id)  from employee group by post ;
+-----------+------------------+
| post      | group_concat(id) |
+-----------+------------------+
| operation | 16,15,14,13,12   |
| sale      | 11,10,9,8,7      |
| teacher   | 6,5,4,3,2,1      |
+-----------+------------------+
3 rows in set (0.00 sec)


mysql> select post,group_concat(id)  from employee group by post having count(id) >5 ;
+---------+------------------+
| post    | group_concat(id) |
+---------+------------------+
| teacher | 6,5,4,3,2,1      |
+---------+------------------+
1 row in set (0.00 sec)
原文地址:https://www.cnblogs.com/mingerlcm/p/9879045.html