在MySQL中,HAVING子句用于在GROUP BY子句之后对结果集进行过滤。它通常与聚合函数一起使用,用于对分组结果进行条件过滤。
以下是HAVING子句的常见用法:
SELECT department, AVG(sales) as average_sales
FROM sales_table
GROUP BY department
HAVING average_sales > 100;
SELECT department, AVG(sales) as average_sales, SUM(sales) as total_sales
FROM sales_table
GROUP BY department
HAVING average_sales > 100 AND total_sales > 1000;
SELECT department, AVG(sales) as average_sales
FROM sales_table
GROUP BY department
HAVING average_sales > (SELECT AVG(sales) FROM sales_table);
SELECT department, COUNT(employee_id) as num_employees
FROM employees_table
GROUP BY department
HAVING num_employees > 5;
总之,HAVING子句可以根据特定的条件对分组结果进行过滤,并返回满足条件的结果。