mysql学习之基础篇05

mysql中的统计函数:

1. 查询商品价格中最高的价格:

select max(shop_price) from goods;

2. 查询商品价格中最低的价格:

select min(shop_price) from goods;

3. 求库存总量:

select sum(goods_number) from goods;

 4. 查看所有商品的平均价格:

select avg(shop_price) from goods;

5. 统计商城内共有多少种商品(不是多少个):

select count(*) from goods;

count()函数是统计行数值,之所以用count(*)而不用count(列名)是因为如果该列有一行为空,那么count(列名)不会把它计算在内。

看个小例子:

就算有某一行全是空,用count(*)也能把它计算在内:

 统计函数单独使用意义不大,要和分组配合起来才有用:

mysql 之 group by 分组查询:

计算一下第三个栏目下所有商品的库存量之和

select cat_id,sum(goods_number) from goods  where cat_id=3 group by cat_id;

 一次计算完每一个栏目下的库存量之和:

select cat_id,sum(goods_number) from goods  group by cat_id;

严格的讲,以group by a,b,c为列,select的列只能在a,b,c或者是统计函数中选择,这样在语义上才没有矛盾。

 做个小练习:有以下成绩表,求出挂科数等于或高于2门的学生的平均成绩:

 

select name,avg(score),sum(score<60)as fail from test5 group by name having fail >=2;

排序:order by

取出第四个栏目下的商品,把价格由高到低进行排序:

select *from goods where cat_id=4 order by shop_price desc; #desc 代表降序排列

按栏目升序排列,同一个栏目下的商品按价格降序排列

select * from goods order by cat_id asc,shop_price desc;

 限制输出条目limit:

取出商品价格前十的商品:

select goods_id,goods_name,cat_id,shop_price from goods order by shop_price desc limit 10;

最后强调一点:Where,group by,having,order by,limit 五个子句顺序不能乱!

猜你喜欢

转载自www.cnblogs.com/wanghaoyu666/p/11274575.html