HAVING子句可以讓我們挑選出該函數的結果符合某些條件的特定行。
WHERE子句所選列的條件,而HAVING子句地方條件由GROUP BY子句創建的組。
以下是HAVING子句在SELECT查詢的位置:
SELECT FROM WHERE GROUP BY HAVING ORDER BY
HAVING子句必須遵循在GROUP BY子句於一個查詢,也必須先如果使用ORDER BY子句。以下是SELECT語句的語法,包括HAVING子句:
SELECT column1, column2 FROM table1, table2 WHERE [ conditions ] GROUP BY column1, column2 HAVING [ conditions ] ORDER BY column1, column2
考慮表COMPANY 有如下記錄:
# select * from COMPANY; id | name | age | address | salary ----+-------+-----+-----------+-------- 1 | Paul | 32 | California| 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall| 45000 7 | James | 24 | Houston | 10000 (7 rows)
下面的例子顯示記錄的名稱計數小於2:
testdb-# SELECT NAME FROM COMPANY GROUP BY name HAVING count(name) < 2;
這將產生以下結果:
name ------- Teddy Paul Mark David Allen Kim James (7 rows)
現在,讓我們來創建COMPANY 表於的三條記錄使用下面的INSERT語句:
INSERT INTO COMPANY VALUES (8, 'Paul', 24, 'Houston', 20000.00); INSERT INTO COMPANY VALUES (9, 'James', 44, 'Norway', 5000.00); INSERT INTO COMPANY VALUES (10, 'James', 45, 'Texas', 5000.00);
現在我們的表名稱重復的記錄:
id | name | age | address | salary ----+-------+-----+--------------+-------- 1 | Paul | 32 | California | 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall | 45000 7 | James | 24 | Houston | 10000 8 | Paul | 24 | Houston | 20000 9 | James | 44 | Norway | 5000 10 | James | 45 | Texas | 5000 (10 rows)
下面的例子會顯示名稱數量大於1的記錄:
testdb-# SELECT NAME FROM COMPANY GROUP BY name HAVING count(name) > 1;
這將產生以下結果:
name ------- Paul James (2 rows)