一、引言
今天主要讲一讲昨天剩下的排序、聚合、分组等单表查询的一些操作.
二、单表查询
1.排序查询
知识点:
排序查询关键字: order by
排序查询基础格式: select 字段名 from 表名 order by 排序字段名 asc|desc;
asc : 升序(默认) desc: 降序
进阶格式: select 字段名 from 表名 order by 排序字段1名 asc|desc , 排序字段2名 asc|desc;
注意: 如果order by后跟多个排序字段,先按照前面的字段排序,如果有相同值的情况再按照后面的排序规则排序
-- 示例1:查询所有商品,并按照评分从高到低进行排序
select * from products order by score desc;
-- 示例2:查询所有商品,先按照评分从高到低进行排序,评分相同的按照价格从低到高排序 select * from products order by score desc, price;
2.聚合函数
知识点:
聚合函数: 又叫统计函数,也叫分组函数
常用聚合函数: sum( ) count( ) avg( ) max( ) min( )
聚合查询基础格式: select 聚合函数(字段名) from 表名;
注意: 此处没有分组默认整个表就是一个大的分组
注意: 聚合函数(字段名)会自动忽略null值,以后统计个数一般用count(*)统计因为它不会忽略null值
示例:
# 注意: 别名不建议用中文,以下仅仅为了演示
-- 示例1:统计当前商品一共有多少件
select count(id) from products;
select count(*) from products;
-- 示例2:对商品评分列进行计数、求最大、求最小、求和、求平均
select
count(score) as cnt,
max(score) as max_score,
min(score) as min_score,
sum(score) as total_score,
avg(score) as avg_score
from products;
-- 示例3:统计所有非自营商品评分的平均值
select
is_self,
avg(score)
from
products
where
is_self = '非自营';3.分组查询
分组查询关键字: group by
分组查询基础格式: select 分组字段名,聚合函数(字段名) from 表名 group by 分组字段名;
注意: select后的字段名要么在group by后面出现过,要么写到聚合函数中,否则报错.
分组查询进阶格式: select 分组字段名,聚合函数(字段名) from 表名 [where 非聚合条件] group by 分组字段名 [having 聚合条件];
where和having的区别?
书写顺序: where在group by 前,having在group by后
执行顺序: where在分组前,having在分组后
分组函数: where后不能跟聚合条件,只能跟非聚合条件,having后可以使用聚合条件,也可以使用非聚合条件(不建议)
应用场景: 建议大多数过滤数据都采用where,只有当遇到聚合条件的时候再使用having
使用别名: where后不能使用别名,having后可以使用别名
-- 示例1:统计每个分类的商品数量
select
category_id,
-- ② 再聚合:对每一组的id进行count计数
count(id) as cnt
from products
-- ① 先分组:按照category_id进行分组
group by category_id;
-- 示例2:统计每个分类中自营和非自营商品的数量
select
category_id,
is_self,
count(id) as cnt
from products
group by category_id, is_self;
-- 示例3:统计每个分类商品的平均价格,并筛选出平均价格低于1000的分类
select category_id,
-- 再聚合
avg(price)
from products
-- 先分组
group by category_id
-- 对分组聚合的结果进行筛选
having avg(price) < 1000;4.limit查询
知识点:
分页查询关键字: limit
分页查询基础格式: select 字段名 from 表名 limit x,y;
x: 起始索引,默认从0开始 x = (页数-1)*y
y: 本次查询的条数
注意: limit能完成topn需求,但是不能考虑到并列情况,此问题可以使用后期学习的开窗函数解决
示例:
- 示例1:获取所有商品中,价格最高的商品信息
select
*
from products
order by price desc
limit 1; -- limit 0, 1;
-- 示例2:将商品数据按照价格从低到高排序,然后获取第2页内容(每页3条)
select
*
from products
order by price
limit 3, 3;
-- 示例3:当分页展示的数据不存在时,不报错,只不过查询不到任何数据
select * from products limit 20, 10;5.sql顺序
书写顺序: select -> distinct -> 聚合函数 -> from -> where -> group by -> having -> order by -> limit
执行顺序: from -> where -> group by -> 聚合函数 -> having -> select -> distinct -> order by -> limit
大家记住最后这个执行顺序就好,前面的各种格式都是根据这个来的.
三、结语
今天就先讲这么多吧,下次给大家讲用python操作mysql.
到此这篇关于sql单表查询全攻略:排序聚合分组的文章就介绍到这了,更多相关sql单表查询内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论