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 

EmpIDNameCityAgeSalary
1JohnLondon253000
2MarryLondon242750
3JoLondon272800
4KimAmsterdam303100
5RameshNew Delhi283000
6HuangAmsterdam282800

表 2:Bonus_Paid 表

EmpIDBonus
1500
2400
3450
4550
5400
6600

获取包含每个城市的员工数量的列表(来自Employee表)包括拥有超过一名员工的城市,查询如下:

SELECT COUNT(EmpID) AS Number_of_Employee, City  
FROM Employee
GROUP BY City
HAVING COUNT(EmpID) > 1; 

这将产生如下所示的结果:

Number_of_EmployeeCity
2Amsterdam
3London

要获得按降序排序的上表根据员工数量排序,查询将是:

SELECT COUNT(EmpID), City  
FROM Employee
GROUP BY City
HAVING COUNT(EmpID) > 1
ORDER BY COUNT(EmpID) DESC; 

查询结果将是:

Number_of_EmployeeCity
3London
2Amsterdam

将 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; 

以下代码的结果将是:

CityBonusAmount
Amsterdam1150
London1350