SELECT 语句中的 HAVING 子句是否“无用”?
Is the HAVING clause “useless” in a SELECT statement?
我正在阅读一篇名为 Query Optimization Techniques - Tips For Writing 的论文
高效快速 SQL 查询.
该文档表明 HAVING 子句在 SELECT 语句中“无用”:
Tip #2: Avoid including a HAVING clause in SELECT statements
The HAVING clause is used to filter the rows after all the rows are
selected and it is used like a filter. It is quite useless in a SELECT
statement. It works by going through the final result table of the
query parsing out the rows that don’t meet the HAVING condition.
Example:
Original query:
SELECT s.cust_id,count(s.cust_id)
FROM SH.sales s
GROUP BY s.cust_id
HAVING s.cust_id != '1660' AND s.cust_id != '2';
Improved query:
SELECT s.cust_id,count(cust_id)
FROM SH.sales s
WHERE s.cust_id != '1660'
AND s.cust_id !='2'
GROUP BY s.cust_id;
问题:
这个说法正确吗? HAVING 子句在 SELECT 语句中没有用途吗?
如果它没用,它就不会存在。
Use the HAVING clause to restrict the groups of returned rows to those groups for which the specified condition is TRUE
根据您的示例,您可以将其用作示例
SELECT s.cust_id,count(cust_id)
FROM SH.sales s
WHERE s.cust_id != '1660'
AND s.cust_id !='2'
GROUP BY s.cust_id
HAVING count(cust_id) > 5; --> here
它的目的是什么?您不能将 WHERE
与聚合函数一起使用,例如这是无效的:
FROM ...
WHERE count(cust_id) > 5 --> this
AND ...
我正在阅读一篇名为 Query Optimization Techniques - Tips For Writing 的论文 高效快速 SQL 查询.
该文档表明 HAVING 子句在 SELECT 语句中“无用”:
Tip #2: Avoid including a HAVING clause in SELECT statements
The HAVING clause is used to filter the rows after all the rows are selected and it is used like a filter. It is quite useless in a SELECT statement. It works by going through the final result table of the query parsing out the rows that don’t meet the HAVING condition.
Example:
Original query:
SELECT s.cust_id,count(s.cust_id) FROM SH.sales s GROUP BY s.cust_id HAVING s.cust_id != '1660' AND s.cust_id != '2';
Improved query:
SELECT s.cust_id,count(cust_id) FROM SH.sales s WHERE s.cust_id != '1660' AND s.cust_id !='2' GROUP BY s.cust_id;
问题:
这个说法正确吗? HAVING 子句在 SELECT 语句中没有用途吗?
如果它没用,它就不会存在。
Use the HAVING clause to restrict the groups of returned rows to those groups for which the specified condition is TRUE
根据您的示例,您可以将其用作示例
SELECT s.cust_id,count(cust_id)
FROM SH.sales s
WHERE s.cust_id != '1660'
AND s.cust_id !='2'
GROUP BY s.cust_id
HAVING count(cust_id) > 5; --> here
它的目的是什么?您不能将 WHERE
与聚合函数一起使用,例如这是无效的:
FROM ...
WHERE count(cust_id) > 5 --> this
AND ...