在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子句可以根據特定的條件對分組結果進行過濾,并返回滿足條件的結果。