zoukankan      html  css  js  c++  java
  • Where 与 Having

    WHERE在数据分组前进行过滤,HAVING在数据分组后过滤。

    HAVING可以对检索(或计算)出的结果过滤,WHERE则不行。

    WHERE、聚合函数、HAVING在from后面的执行顺序:WHERE>聚合函数(sum,min,max,avg,count)>HAVING

    表orders的数据如下:

    +-----------+---------------------+---------+
    | order_num | order_date | cust_id |
    +-----------+---------------------+---------+
    | 20005 | 2005-09-01 00:00:00 | 10001 |
    | 20006 | 2005-09-12 00:00:00 | 10003 |
    | 20007 | 2005-09-30 00:00:00 | 10004 |
    | 20008 | 2005-10-03 00:00:00 | 10005 |
    | 20009 | 2005-10-08 00:00:00 | 10001 |
    +-----------+---------------------+---------+

    计算每个cust_id的订单数,且返回订单数>=2的cust_id,这里只能使用HAVING

    mysql> SELECT cust_id, COUNT(*) AS nums
             -> FROM orders
             -> group by cust_id
             -> HAVING COUNT(*) >= 2;
    +---------+------+
    | cust_id | nums |
    +---------+------+
    | 10001 | 2 |
    +---------+------+

    where首先排除了不符合要求的行,在此基础上可以分组、计算, 而后having可以进一步筛选前面得到的结果。

  • 相关阅读:
    bzoj 2216 Lightning Conductor
    一些有趣的问题合集
    Codeforces 40E Number Table
    Codeforces 37D Lesson Timetable
    bzoj 4289 Tax
    bzoj 2844 albus就是要第一个出场
    bzoj 2115 Xor
    luogu 3790 文艺数学题
    bzoj 1420 Discrete Root
    Lucas定理学习笔记
  • 原文地址:https://www.cnblogs.com/deltadeblog/p/9641873.html
Copyright © 2011-2022 走看看