MySQL HAVING
简介:在本教程中,您将学习如何使用MySQL HAVING子句为行组或聚合组指定过滤条件。
MySQL HAVING子句简介
SELECT
语句中使用 HAVING
子句来指定一组行或聚合的过滤条件。
HAVING
子句通常与GROUP BY
子句一起使用,以根据指定的条件过滤组。如果GROUP BY
省略HAVING
子句,则子句的行为类似于WHERE
子句。
注意:
HAVING
子句将过滤条件应用于每组行,而WHERE
子句将过滤条件应用于每个单独的行。
MySQL HAVING子句实例
让我们举一些使用HAVING
子句的例子 来看看它是如何工作的。我们将使用示例数据库中的orderdetails
表进行演示。
+-----------------+ | orderdetails | +-----------------+ | orderNumber | | productCode | | quantityOrdered | | priceEach | | orderLineNumber | +-----------------+ 5 rows in set (0.01 sec)可以使用
GROUP BY
子句获取订单号,每个订单销售的商品数量以及每个订单的总销售额:
SELECT ordernumber, SUM(quantityOrdered) AS itemsCount, SUM(priceeach*quantityOrdered) AS total FROM orderdetails GROUP BY ordernumber;运行结果:
+-------------+------------+----------+ | ordernumber | itemsCount | total | +-------------+------------+----------+ | 10100 | 151 | 10223.83 | | 10101 | 142 | 10549.01 | | 10102 | 80 | 5494.78 | | 10103 | 541 | 50218.95 | | 10104 | 443 | 40206.20 | | 10105 | 545 | 53959.21 | | 10106 | 675 | 52151.81 | | 10107 | 229 | 22292.62 | ...现在,您可以使用以下
HAVING
子句查找总销售额大于1000
哪个订单:
SELECT ordernumber, SUM(quantityOrdered) AS itemsCount, SUM(priceeach*quantityOrdered) AS total FROM orderdetails GROUP BY ordernumber HAVING total > 1000;运行结果:
+-------------+------------+----------+ | ordernumber | itemsCount | total | +-------------+------------+----------+ | 10100 | 151 | 10223.83 | | 10101 | 142 | 10549.01 | | 10102 | 80 | 5494.78 | | 10103 | 541 | 50218.95 | | 10104 | 443 | 40206.20 | | 10105 | 545 | 53959.21 | | 10106 | 675 | 52151.81 | ...还可以使用逻辑运算符(如
OR
和AND
)在HAVING
中构造复杂条件。假设您要查找总销售额大于1000
且包含多个600
项目的订单,您可以使用以下查询:
SELECT ordernumber, SUM(quantityOrdered) AS itemsCount, SUM(priceeach*quantityOrdered) AS total FROM orderdetails GROUP BY ordernumber HAVING total > 1000 AND itemsCount > 600;运行结果:
+-------------+------------+----------+ | ordernumber | itemsCount | total | +-------------+------------+----------+ | 10106 | 675 | 52151.81 | | 10126 | 617 | 57131.92 | | 10135 | 607 | 55601.84 | | 10165 | 670 | 67392.85 | | 10168 | 642 | 50743.65 | | 10204 | 619 | 58793.53 | | 10207 | 615 | 59265.14 | ...假设您要查找已发货且总销售额大于1500的所有订单,您可以使用
INNER JOIN
子句将orderdetails
表与orders
表连接,并对status
列和total
聚合应用条件, 如以下查询所示:
SELECT a.ordernumber, status, SUM(priceeach*quantityOrdered) total FROM orderdetails a INNER JOIN orders b ON b.ordernumber = a.ordernumber GROUP BY ordernumber, status HAVING status = 'Shipped' AND total > 1500;运行结果:
+-------------+---------+----------+ | ordernumber | status | total | +-------------+---------+----------+ | 10100 | Shipped | 10223.83 | | 10101 | Shipped | 10549.01 | | 10102 | Shipped | 5494.78 | | 10103 | Shipped | 50218.95 | | 10104 | Shipped | 40206.20 | | 10105 | Shipped | 53959.21 | | 10106 | Shipped | 52151.81 | | 10107 | Shipped | 22292.62 | ...只有在将
GROUP BY
子句与HAVING
子句一起使用才能生成高级报告的输出时,子句才有用。例如,您可以使用HAVING
来回答统计问题,例如查找本月,本季度或本年总销售额超过10K的订单数量。
在本教程中,您学习了如何将MySQL HAVING
子句与GROUP BY
子句一起使用,以指定行或聚合组的过滤条件。