where和having
where
- where是一个约束声明,使用where来约束来自数据库的数据
- where是在结果返回之前起作用的
- where中不能使用聚合函数
having
- having是一个过滤声明
- 在查询返回结果集以后,对查询结果进行的过滤操作;
- 在having中可以使用聚合函数。
having是从前面筛选的表里面进行字段筛选,即select运行完之后生成的虚拟表里面去筛选
where是从数据库里面的表里面进行字段筛选
where和having的执行顺序:where早于group by早于having。
例子
有student表,表内字段,name(char类型)和age(int类型)
1 where和having都可用情况
select name,age from student where name = 'aaa'
select name,age from student having name = 'aaa'
2 where可用 ,having 不可用
不报错
select age from student where name = 'aaa'
会报错,因为select查询出来的字段没有 name
select age from student having name = 'aaa'
3 having可用 ,where 不可用
会报错,因为数据库里面字段没有 aa
select age as aa from student where aa = 11
不报错
select age as aa from student having aa= 11
不报错,因为生成的虚拟表里面还是存在age,只不过aa是age的别名,此时age,aa都可以用
select age as aa from student having age= 11