The difference between having and where in MySQL

HAVING and WHERE are two keywords used to filter data in SQL queries, but there are some differences when they are used:

WHERE clause:
1 is used to filter the raw data before query execution.
2 acts on a single row of data, filtering data rows that do not meet the conditions.
3 Used when judging and filtering a single row, such as row-based conditional filtering.

HAVING clause:
1 is used to filter the grouping results after data grouping.
2 is usually used together with GROUP BY to conditionally filter the grouped data.
3 Act on grouped data and filter groups that do not meet the conditions.
4 is used when performing aggregated conditional filtering on grouped results, such as conditional filtering based on aggregated results.

Example:
Suppose there is a table Sales that contains sales order information, including order number, product, quantity and amount, etc. We want to find products with sales quantity greater than 100 and order total amount greater than 1000.

Form Sales:

+------+--------+----------+--------+
| OrderID | Product | Quantity | Amount |
+------+--------+----------+--------+
| 1      | A      | 50       | 500    |
| 2      | B      | 150      | 1500   |
| 3      | A      | 200      | 2000   |
| 4      | C      | 80       | 800    |
+------+--------+----------+--------+
使用 WHERE 子句的查询:
SELECT Product, SUM(Quantity) AS TotalQuantity
FROM Sales
WHERE Quantity > 100 AND Amount > 1000
GROUP BY Product;
使用 HAVING 子句的查询:

SELECT Product, SUM(Quantity) AS TotalQuantity
FROM Sales
GROUP BY Product
HAVING SUM(Quantity) > 100 AND SUM(Amount) > 1000;
在这个示例中,WHERE 子句用于在查询执行之前对原始数据进行筛选,而 HAVING 子句用于在对数据进行分组后对分组结果进行筛选。

Guess you like

Origin blog.csdn.net/guoguozgw/article/details/132308718