zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    Notepad++ 中如何将代码格式化
    JAVA 解析复杂的json字符串
    8. java操作mongodb——查询数据
    7.第一次使用java连接mongodb遇到的问题
    13. Intellij IDEA调试功能使用总结
    HttpClient4.5简单使用
    12.Intellij IDEA 添加jar包的三种方式
    11.IntelliJ IDEA详细配置和使用教程(适用于Java开发人员)
    10.Intellij IDEA svn的使用详解
    黑客攻克索尼影业,掌控了操作系统的未来
  • 原文地址:https://www.cnblogs.com/mingerlcm/p/9879045.html
Copyright © 2011-2022 走看看