《mysql必知必会》学习_第13章

第13章:分组过滤。

P83

select count(*) as num_prods from products where vend_id=1003; #返回vend_id=1003的产品数目总值#

P84

select count(*) as num_prods from products group by vend_id; #返回各个vend_id所提供的产品数量,不需要指定计算每个组,因为用了group by ,系统会自动完成#

注意:group by必须在where 之后,order by 之前(当然是在需要where 或order by 的情况下)

P85

 select vend_id,count(*) as num_prods from products group by vend_id with rollup ;  # 使用with rollup关键字,可以得到每个分组以及每个分组汇总级别(针对每个分组)的值###其实我觉得使用了with rollup与否,对结果并没有影响,来个可爱告诉我使用不使用的区别吧### 

 

 P85 过滤分组 -- having语句

select cust_id,count(*) as orders from orders group by cust_id having count(*)>=2l; #where 过滤行,having过滤分组###我理解的是where对表初始的行数据过滤,而having是聚集函数处理以后的分组过滤(感觉不大对)#####对面大神说用了group by了不能用where,要用having。(P87页说和聚集函数一起使用列,必须使用group by,不能使用order by ,相应地,下面的csdn的网友说,聚集函数要用having筛选分组,所以以此类推,用了group by不能用where,要用having的意思吗??? )###  

 

P86

select vend_id,count(*) as num_prods from products where prod_price>=10 group by vend_id having count(*)>=2;  #条件是列prod_price>=10,count(*)>=2 ,这个语句同时出现where和having #

有个我认为不错的解释:https://blog.csdn.net/zqtsx/article/details/41869049

 P88

select order_num,sum(quantity*item_price) as ordertotal from orderitems group by order_num having sum(quantity*item_price)>=50; #group by 让排列按order_num来排列,having设定了组sum(quantity*item_price)或者是ordertotal大于50的条件.

 select order_num,sum(quantity*item_price) as ordertotal from orderitems group by order_num having sum(quantity*item_price)>=50 order by ordertotal ; #group by 让排列按order_num来排列,having设定了聚集函数得到的组sum(quantity*item_price)大于等于50,order by 得到最后的顺序由ordertotal排序输出(ordertatal的顺序默认是升序)#.

 

 

 

 #group by 分组说明,仅限于聚集函数得到的分组;

having :组级过滤;

where:行级过滤,表中的行;

order by :输出的排序过滤。

limit n :要检索的行数;

limit (n,m) :要检索的(开始的行数:第n个开始,检索m行即是第n+m个结束)#

 

posted @ 2018-08-03 16:26  张三疯了  阅读(91)  评论(0编辑  收藏  举报