Home >Daily Programming >Mysql Knowledge >How to use having in mysql
Use the HAVING clause to filter groups in MySQL grouping queries: limit the scope of the group and filter the group based on the group aggregate value, such as finding customer groups with an average order value greater than $100. Compare group aggregate values, such as finding groups of customers with a total order count greater than 10. Use aggregate functions like SUM(), AVG(), COUNT(), etc. The difference with the WHERE clause is that the WHERE clause filters individual rows, while the HAVING clause filters groups.
Usage of HAVING clause in MySQL
The HAVING clause is used to filter groups in grouped queries . It is similar to the WHERE clause, but is used to filter groups of data rather than individual rows.
Syntax:
<code class="sql">SELECT ... GROUP BY ... HAVING condition</code>
Usage:
<code class="sql">SELECT customer_id FROM orders GROUP BY customer_id HAVING AVG(order_value) > 100;</code>
<code class="sql">SELECT customer_id FROM orders GROUP BY customer_id HAVING COUNT(*) > 10;</code>
Example:
Get the average price of each product category and only show categories with an average price greater than $100:
<code class="sql">SELECT category_name, AVG(product_price) AS average_price FROM products GROUP BY category_name HAVING average_price > 100;</code>
The above is the detailed content of How to use having in mysql. For more information, please follow other related articles on the PHP Chinese website!