一、从读取数据来看:
- where 是数据从磁盘读入内存时候一条一条判断的
- having 是将所有数据读入内存,在分组统计前,根据having的条件再将不符合条件的数据删除
这也是在where中不能用select字段的别名(区别二),而having能用别名的原因
二、从使用来看
having 子句可以使用字段别名,where不可以使用别名
- having可以使用聚合函数,where不可用
- HAVING子句可以让我们筛选成组后的各组数据,WHERE子句在聚合前先筛选记录.也就是说作用在GROUP BY 子句和HAVING子句前;而 HAVING子句在聚合后对组记录进行筛选
- having筛选必须是根据前面select字段的值 进行筛选 ```sql — having与where都行 select name,age from students WHERE age>20; select name,age from students HAVING age>20;
— having语句出错 select name,age from students WHERE id>1; select name,age from students HAVING id>1; — > 1054 - Unknown column ‘id’ in ‘having clause’
— where语句出错 select name,age as ag from students WHERE ag>20; — > 1054 - Unknown column ‘ag’ in ‘where clause’ select name,age as ag from students having ag>20; ```