随笔 - 330,  文章 - 1,  评论 - 0,  阅读 - 9025

一. 简介

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是磁盘读入内存后再判断。

2. 执行顺序不一样

WHERE>HAVING

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

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

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

eg:

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

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

eg:

select  *  as aa from student where count(*) > 1 (错误)

select *  from student group name having  count(name) > 1 (正确)

最后:能用where就用where,使用where比用having效率要高很多

posted on   vow007  阅读(18)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示