DQL-分组查询
聚合函数:
介绍:将一列数据作为一个整体,进行纵向计算。
语法:
select
聚合函数
(
字段列表
)
from
表名
;
函数 | 功能 |
count | 统计数量 |
max | 最大值 |
min | 最小值 |
avg | 平均值 |
sum | 求和 |
select count(id) from tb_emp;
select count(job) from tb_emp;
select count(1) from tb_emp;
select count('A') from tb_emp;
select count(*) from tb_emp;
select max(entrydate) from tb_emp;
select avg(socres) from tb_emp;
select sum(score) from tb_emp;
注意事项:
1.null
值不参与所有聚合函数运算。
2.统计数量可以使用:
count(*) count(
字段
) count(
常量
)
,推荐使用
count(*)
。
DQL-分组查询:
分组查询:select 字段列表 from 表名 [ where 条件 ] group by 分组字段名 [ having 分组后过滤条件 ];
select job,count(*) from tb_emp where entrydate <= '2010-01-01'
group by job having count(*) >= 2;
where与having区别:
1.
执行时机不同:
where
是分组之前进行过滤,不满足
where
条件,不参与分组;而
having
是分组之后对结果进行过滤。
2.
判断条件不同:
where
不能对聚合函数进行判断,而
having
可以。
注意事项:
1.
分组之后,查询的字段一般为聚合函数和分组字段,查询其他字段无任何意义。
2.
执行顺序
: where >
聚合函数
> having
。
DQL-排序查询
排序查询:select 字段列表 from 表名 [ where 条件列表 ] [ group by 分组字段 ] order by 字段1 排序方式1 , 字段2 排序方式2
排序方式:
ASC
:升序(默认值)
DESC
:降序
select * from tb_emp order by entrydate asc;
select * from tb_emp order by entrydate;
select * from tb_emp order by entrydate , update_time desc;
注意事项:
如果是多字段排序,当第一个字段值相同时,才会根据第二个字段进行排序。
DQL-分页查询
分页查询:select 字段列表 from 表名 limit 起始索引, 查询记录数 ;
select * from tb_emp limit 0,10;
select * from tb_emp limit 10;
-- 起始索引 =(页码 - 1) * 每页展示记录数
select * from tb_emp limit 10,10;
注意事项:
1.
起始索引从
0
开始,起始索引
=
(查询页码
- 1
)* 每页显示记录数。
2.
分页查询是数据库的方言,不同的数据库有不同的实现,
MySQL
中是
LIMIT
。
3.
如果查询的是第一页数据,起始索引可以省略,直接简写为
limit 10
。
PS:
函数:
if(表达式, tvalue, fvalue):当表达式为true时,取值tvalue;当表达式为false时,取值fvalue
case expr when value1 then result1 [when value2 then value2 ...] [else result] end