0、本章学习目录大纲 - 分组查询
初学耗时:1.5h
注:CSDN手机端暂不支持章节内链跳转,但外链可用,更好体验还请上电脑端。
一、分组查询
1.1 创建表和插入数据。
1.2 查询购买的每种商品的总价。
1.3 查询每一种商品的总价大于30的商品,并显示总价。
二、面试题
2.1 where与having的区别?
2.2 查询的执行顺序。
- 1、A04系列全套网盘资源:
A04系列全套网盘资源
提取码:jhuk
一、分组查询
1.1 ~ 创建表和插入数据。
create table orders(
id int,
product varchar(20),
price float
);
insert into orders(id,product,price) values(1,'纸巾',16);
insert into orders(id,product,price) values(2,'纸巾',16);
insert into orders(id,product,price) values(3,'红牛',5);
insert into orders(id,product,price) values(4,'洗衣粉',60);
insert into orders(id,product,price) values(5,'苹果',8);
insert into orders(id,product,price) values(6,'洗衣粉',60);
1.2 ~ 查询购买的每种商品的总价。
1.2.1 . 生活举例:什么是分组?
假设去超市买东西,我买了肥皂、洗衣粉、洗衣液、苹果、香蕉、葡萄等。
…
我们在计算总价格之前先对所买的商品进行分类计算价格,然后在相加计算总价格。
…
比如我们先将肥皂、洗衣粉、洗衣液分为一组计算出价格,然后再将苹果、香蕉、葡萄分为一组计算出价格,最后将两组的价格相加就是商品的总价格。
…分组其实就是按列进行分类,然后可以对分类完的数据使用聚合函数进行运算。
1.2.2 . 执行语句。
select product,sum(price) from orders group by product;
1.2.3 . 执行结果。
洗衣粉 120
红牛 5
纸巾 32
苹果 8
1.2.4 . 修改上述的查询语句:查询结果添加一个id。
select id,product,sum(price) from orders group by product;
1.2.5 . 查询比较。
通过查询的结果和原来的数据比较发现,虽然添加id之后可以查询出结果,但是对于纸巾商品来说有问题,查询结果显示id是1,而纸巾的结果的id除了1还有2,同是纸巾,牌子还不一样,所以查询结果有问题。
1.2.6 . 再次修改:将纸巾id为2的price价格修改为20。
select product,sum(price) from orders group by product,price;
1.2.7 . 查看结果。
1.2.8 . 得出结论。
以上结果说明:先按照商品名字进行分组,然后再按照商品的价格进行分组。
1.3 ~ 查询每一种商品的总价大于30的商品,并显示总价。
1.3.1 . 执行语句。
# 为什么报错?!
select product,sum(price) from orders where sum(price)>30 group by product;
# 正确写法:
select product,sum(price) from orders group by product having sum(price)>30;
1.3.2 . 结果验证。
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
二、面试题
2.1 ~ where与having的区别?
1、having 通常与group by 分组结合使用。 where 和分组无关。
2、having是否可以替换之前的where呢?可以,但有要求。
…
上面的having可以用的前提是我已经筛选出了price字段,在这种情况下和where的效果是等效的,但是如果我没有select price 就会报错!
…
因为having是从筛选出来的字段再筛选,而where是从数据表中的字段直接进行的筛选的。
…总结:开发中建议上述情况下使用where,避免没有必要的错误。
3、where 后面的条件可以写在having 中,但是 having中的条件不一定能写在where中。
…
例如having中的 聚合函数(count,sum,avg,max,min),是不可以出现where条件中。4、where 是在分组之前进行过滤的。having 是在分组之后进行过滤的。
2.2 ~ 查询的执行顺序。
1)from : 表名。
2)where:条件过滤。
3)group by : 分组。
4)having : 分组之后进行过滤。
5)select :执行完毕之后,显示内容。
6)order by : 根据查询的内容进行排序输出。
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
^ 至此,数据库表内容操作 - 分组查询完成。
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
※ 世间诱惑何其多,坚定始终不动摇。
在给定文件中查找与设定条件相符字符串的命令?
…
A、gzip
B、grep
C、ls
D、find
…
B
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
注:CSDN手机端暂不支持章节内链跳转,但外链可用,更好体验还请上电脑端。
我知道我的不足,我也知道你的挑剔,但我就是我,不一样的烟火,谢谢你的指指点点,造就了我的点点滴滴:)!