SQL查询中having和where的异同点

来源:互联网 发布:mysql my.ini 编码 编辑:程序博客网 时间:2024/05/22 05:29

SQL查询中having与where 的异同点

在sql查询中, having与where类似,可以筛选数据,where后的表达式怎么写,having后就怎么写。
1. where针对表中的列发挥作用,查询数据。
2. having对查询结果中的列发挥作用,筛选数据。

-- 查询本店商品价格比市场价低多少钱,输出低200元以上的商品select goods_id,good_name,market_price - shop_price as s from goods having s>200 ;--这里不能用where因为s是查询结果,而where只能对表中的字段名筛选

如果用where的话则是:

select goods_id,goods_name from goods where market_price - shop_price > 200;

同时使用where与having

 select cat_id,goods_name,market_price - shop_price as s  from goods  where cat_id = 3  having s > 200;

查询积压货款超过2万元的栏目,以及该栏目积压的货款

    select cat_id,sum(shop_price * goods_number) as s     from goods      group by cat_id      having s > 20000 

查询两门及两门以上科目不及格的学生的平均分
思路:

-- 先计算所有学生的平均分select name,avg(score) as pj from stu group by name;-- 查出所有学生的挂科情况select name,score<60 from stu;-- 这里score<60是判断语句,所以结果为真或假,mysql中真为1假为0-- 查出两门及两门以上不及格的学生select name,sum(score<60) as gk from stu group by name having gk > 1;-- 综合结果select name,sum(score<60) as gk,avg(score) as pj from stu group by name having gk >1; 
0 0
原创粉丝点击