Mysql

关注公众号 jb51net

关闭
首页 > 数据库 > Mysql > Mysql having与where区别

Mysql中having与where的区别小结

作者:李若盛开

本文主要介绍了MySQL中WHERE和HAVING子句的区别,包括它们的执行顺序、效率、适用条件和在多表关联查询中的应用,具有一定的参考价值,感兴趣的可以了解一下

一. 简介

where

对查询数据进行过滤

having

用于对已分组的数据进行过滤【having和group by 必须配合使用(有having必须出现group by)】

二. 用法

where

select * from table where sum(字段)>100

having

select * from table group by 字段 having 字段>10

三.区别

1. 被执行的数据来源不同

where是数据从磁盘读入内存的时候进行判断,【数据分组前进行过滤】

而having是磁盘读入内存后再判断。【对分组之后的数据再进行过滤】

所以:使用where比用having效率要高很多。

2. 执行顺序不一样

Where>Group By>Having

MySQL解释sql语言时的执行顺序:

SELECT
DISTINCT <select_list>
FROM <left_table>
<join_type> JOIN <right_table>
ON <join_condition><strong>
WHERE</strong> <where_condition>
GROUP BY <group_by_list><strong>
HAVING</strong> <having_condition>
ORDER BY <order_by_condition>
LIMIT <limit_number>

3. where不可以使用字段的别名,但是having可以

select name as aa from student where aa > 100 (错误)
select name as aa from student group name having  aa > 100 (正确)

4. having能够使用聚合函数当做条件,但是where不能使用,where只能使用存在的列当做条件

select  *  as aa from student where count(*) > 1 (错误)
select *  from student group name having  count(name) > 1 (正确)

注意:能用where就用where

5. 多表关联查询时,where先筛选再联接,having先联接再筛选

找出所有在'IT'部门且薪水高于10000的员工:(在联接之前先进行了筛选)

SELECT e.employee_name, d.department_name  
FROM employees e  
JOIN departments d ON e.department_id = d.department_id  
WHERE e.salary > 10000 AND d.department_name = 'IT';

找出每个客户下订单的总金额超过1000的客户及其订单总金额:(先联表,基于分组后的聚合结果来过滤)

SELECT c.customer_name, SUM(o.order_amount) AS total_amount  
FROM customers c  
JOIN orders o ON c.customer_id = o.customer_id  
GROUP BY c.customer_name  
HAVING SUM(o.order_amount) > 1000;

总结

到此这篇关于Mysql中having与where的区别小结的文章就介绍到这了,更多相关Mysql having与where区别内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文