MariaDB HAVING 子句用于通过聚合函数指定条件。请注意,MariaDB WHERE 子句不能用于通过聚合函数指定条件。
语法
在 MariaDB 中使用 HAVING 子句的语法如下:
SELECT column_name(s)
FROM table_name
WHERE condition(s)
GROUP BY column_name(s)
HAVING condition(s)
ORDER BY column_name(s);
请注意,HAVING 子句必须位于查询中的 GROUP BY 子句之后,并且如果使用,还必须位于 ORDER BY 子句之前.
示例:
考虑一个数据库,其中包含名为 Employee 和 Bonus_Paid 的表,并具有以下记录:
表 1:Employee 表
EmpID | Name | City | Age | Salary |
---|---|---|---|---|
1 | John | London | 25 | 3000 |
2 | Marry | London | 24 | 2750 |
3 | Jo | London | 27 | 2800 |
4 | Kim | Amsterdam | 30 | 3100 |
5 | Ramesh | New Delhi | 28 | 3000 |
6 | Huang | Amsterdam | 28 | 2800 |
表 2:Bonus_Paid 表
EmpID | Bonus |
---|---|
1 | 500 |
2 | 400 |
3 | 450 |
4 | 550 |
5 | 400 |
6 | 600 |
获取包含每个城市的员工数量的列表(来自Employee表)包括拥有超过一名员工的城市,查询如下:
SELECT COUNT(EmpID) AS Number_of_Employee, City
FROM Employee
GROUP BY City
HAVING COUNT(EmpID) > 1;
这将产生如下所示的结果:
Number_of_Employee | City |
---|---|
2 | Amsterdam |
3 | London |
要获得按降序排序的上表根据员工数量排序,查询将是:
SELECT COUNT(EmpID), City
FROM Employee
GROUP BY City
HAVING COUNT(EmpID) > 1
ORDER BY COUNT(EmpID) DESC;
查询结果将是:
Number_of_Employee | City |
---|---|
3 | London |
2 | Amsterdam |
将 HAVING 子句与 JOIN 结合使用:要获取包含每个城市向员工支付的奖金的列表,并且仅包含拥有一名以上员工的城市,查询如下:
SELECT A.City, SUM(B.Bonus) AS BonusAmount
FROM Employee AS A
INNER JOIN Bonus_Paid AS B
ON A.EmpID = B.EmpID
GROUP BY City
HAVING COUNT(A.EmpID) > 1;
以下代码的结果将是:
City | BonusAmount |
---|---|
Amsterdam | 1150 |
London | 1350 |