English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在本教程中,您将学习如何过滤GROUP BY子句返回的组。
HAVING子句通常与GROUP BY子句一起使用,以指定组或集合的过滤条件。HAVING子句只能与SELECT语句一起使用。
为了容易理解这一点,让我们来看看下面employees和departments表。
+--------+--------------+------------+---------+ | emp_id | emp_name | hire_date | dept_id | +--------+--------------+------------+---------+ | 1 | Ethan Hunt | 2001-05-01 | 4 | | 2 | Tony Montana | 2002-07-15 | 1 | | 3 | Sarah Connor | 2005-10-18 | 5 | | 4 | Rick Deckard | 2007-01-03 | 3 | | 5 | Martin Blank | 2008-06-24 | NULL | +--------+--------------+------------+---------+ | +---------+------------------+ | dept_id | dept_name | +---------+------------------+ | 1 | Administration | | 2 | Customer Service | | 3 | Finance | | 4 | Human Resources | | 5 | Sales | +---------+------------------+ | |
Table: employees | Table: departments |
Now, not only find the names of employees and their departments, but also find the names of departments without any employees.
For small tables, you can simply applyLeft Joinand manually check each department, but if a table contains thousands of employees, that would not be so easy.
In this case, you can use the HAVING clause along withGROUP BYclauses together, as shown below:
SELECT t1.dept_name, count(t2.emp_id) AS total_employees FROM departments AS t1 LEFT JOIN employees AS t2 ON t1.dept_id = t2.dept_id GROUP BY t1.dept_name HAVING total_employees = 0;
If you execute the above statement, you will get the following output:
+------------------+-----------------+ | dept_name | total_employees | +------------------+-----------------+ | Customer Service | 0 | +------------------+-----------------+
Tip:The HAVING clause is similar to the WHERE clause, but it only applies to the entire group, whereasWHEREthe clause applies to individual rows.