having 与where 的异同点

    having与where类似,可以筛选数据,where后的表达式怎么写,having后就怎么写
                    where针对表中的列发挥作用, 查询数据
                    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 t 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;
       4、order by
                    (1) order by price  //默认升序排列
                    (2)order by price desc //降序排列
                    (3)order by price asc //升序排列,与默认一样
                    (4)order by rand() //随机排列,效率不高
                        #按栏目号升序排列,每个栏目下的商品价格降序排列
                        select * from goods where cat_id !=2 order by cat_id,price desc;
                 5、limit
                    limit [offset,] N
                    offset 偏移量,可选,不写则相当于limit 0,N
                    N     取出条目 
 
                    #取价格第4-6高的商品
                    select good_id,goods_name,goods_price from goods order by good_price desc limit 3,3;
                    
            ###查询每个栏目下最贵的商品
                思路:
                        #先对每个栏目下的商品价格排序
                        select cat_id,goods_id,goods_name,shop_price from goods order by cat_id,shop_price desc;
                        #上面的查询结果中每个栏目的第一行的商品就是最贵的商品
                        #把上面的查询结果理解为一个临时表[存在于内存中]【子查询】
                        #再从临时表中选出每个栏目最贵的商品
                        select * from (select goods_id,goods_name,cat_id,shop_price from goods order by cat_id,shop_price desc) as t group by cat_id;
                        #这里使用group by cat_id是因为临时表中每个栏目的第一个商品就是最贵的商品,而group by前面没有使用聚合函数,所以默认就取每个分组的第一行数据,这里以cat_id分组
 
                 良好的理解模型:
                    1、where后面的表达式,把表达式放在每一行中,看是否成立
                    2、字段(列),理解为变量,可以进行运算(算术运算和逻辑运算)  
                    3、 取出结果可以理解成一张临时表

猜你喜欢

转载自www.cnblogs.com/tanada/p/11463045.html
今日推荐