Mysql的where和having区别
where和having都可以使用的场景:
select age,name from User where price > 22
select age,name from User having age> 100
说明:having可用的前提是已经筛选出了age字段,在这种情况下和where的效果是等效的,But如果没有select age 就会报错!!因为having是从前筛选的字段再筛选,而where是从数据表中的字段直接进行的筛选的。
只可以用where,不可以用having的情况
select name from User where age> 22
select name from User having age> 22//报错!!!因为select没有筛选出age字段,having不能用,而where是对表进行检索age>22
只可以用having,不可以用where情况
查询每种id 用户年龄的平均值,获取平均年龄大于22岁的用户信息
select id, avg(age) as agage from User group by id having agage > 22
select id, avg(age) as agage from User where agage >22 group by id //报错!!因为from User 没有这个字段