1.、查询比市场价省钱 200 元以上的商品及该商品所省的钱 (where 和 having 分别实现 )
- select goods_id,shop_price,market_price,(market_price-shop_price) from goods where (market_price-shop_price)>200;
这个 sql 语句 , 计算了两次 , 没有必要,而且也浪费资源;
我们知道 , 在 php 中 , 两个变量计算的结果可以赋值给另一个变量
- select goods_id,shop_price,market_price,(market_price-shop_price) as sheng from goods where sheng>200;
以上sql会报错 , 找不到 sheng;这是错误的写法!
2、这是为什么呢 ?
我们知道 mysql 是数据库服务器 , 帮我们管理数据 ; 说到底 , 他把我们的数据管理到哪里去了呢 ? 管理到了文件上;
我们的商品表 -> data/shop/goods.MYD;
where -> 条件筛选的是磁盘上的表的字段;而 sheng 是结果集上的字段;
我们需要筛选结果集上的字段 , 我们可以将结果集当成表 , 再一步筛选 , 只不过不能用 where, 需要用 having;
where 发挥的比较早 , 是针对内存中的表发挥的作用 -> 筛选出结果集 -> 从结果集中进一步筛选 -> 需要用到 having;
3、正确的SQL写法如下:
- select goods_id,shop_price,market_price,(market_price-shop_price) as sheng from goods having sheng>200;
where 和 having 都存在 ,where 要放在 having 的前面 ;
因为 where 是对内存中的表进行筛选 , 而 having 是对进一步计算出来的结果集进行再一步筛选;
课题案例:
要求 : 查询出 2 门及 2 门以上不及格者的平均成绩;
表如下图:平均成绩需要把他们三门成绩都算上;
1. 先求出所有人的平均成绩
- select name,avg(score) from result group by name;
2. 再看表中哪些人的科目是 score<60;
凡运算必有运算结果 , 比较运算的结果 返回真假 1,0
- select result.*,score<60 from result;
3. 加挂科两门的人筛选出来;
挂科数 sum(score<60) as gk
- select name,avg(score),sum(score<60) as gk from result group by name having gk>=2;