DQL 数据查询语言 ,用来查询数据库中的记录。关键字
select.
1 . 基本查询 select
select age from info
select age as '姓名' from info
2 . 条件查询 where
注意 : 条件可以为多个,可以通过逻辑运算符连接
select * from info where name is null
// 查询不是null
select * from info where name is not null
select * from info where age in(18,20,40)
select * from info where age = 18 or age = 20 or age = 40
!!!模糊匹配
// 两条下划线 ,匹配名字是两位的!!!
select * from info where neme like '__' ;
// % 匹配任意多位 , 此条语句匹配的是 名字最后一位是x的,前面可以有任意多位 。
select * from info where neme like '%x';
3 . 分组查询 group by 、having
3 . 1 聚合函数
将一列数据作为一个整体 ,进行纵向计算。
常见聚合函数 :
语法:
注意 : null值不参与聚合函数的计算
综合运用:
select sum(age)from info where workplace = '西安'
3 . 2 分组查询
注意: where 和 having 的区别
- 执行时机不同 :where是在分组之前进行过滤 ,不满足 where 的条件 ,不参与分组 ;而 having 是在分组之后对分组的结果再进行过滤。
- 判断条件不同 :where 不能对聚合函数进行判断 ,而having可以!!!
// 查询男女员工分别的总人数
select gender , count( * ) from info group by gender ;
// 查询男女员工分别的平均年龄
select gender , avg( age ) from info group by gender ;
// 查询年龄小于 45 的员工 ,并根据工作地址分组 ,获取员工数量大于等于 3 的工作地址
select workplace , count( * ) from info where age < 45 group by workplace having count( * ) >= 3 ;
4 . 排序查询 : order by
可以支持多字段排序 ,即当第一个字段的值相同时 ,再按照第二个字段的顺序进行排序 。
- 升序 asc ;
- 降序 desc ;
select * from info order by age asc ;
// 根据年龄对员工进行升序排序 ,如果年龄相同 ,再按照入职时间进行降序排序 。
select * from info order by age asc , entrydate desc ;
5 . 分页查询 limit :
- 假设每页记录 10 条数据 ,那么要查询第 2 页 ,那么起始索引就为 (2 - 1)* 10 = 10 。
- 分页查询不同数据库 ,有不同的语法!!!
6 . 案例
- select * from info where gender = '女' && age in(20,21,22,23);
- select * from info where gender = '男' && age between 20 and 40 && name like '_ _ _' ;
- select gender , count( * ) from info where age < 60 group by gender ;
- select name , age , entrydate from info where age <= 35 order by age asc , entrydate desc ;
- select * from info where gender = '男' && age bentween 20 and 40 order by age asc , entrydate asc limit 5 ;
注意 : limit应编写在所有指令后面
7 . DQL 编写顺序
8 . DQL 执行顺序
select 在 group by 后执行 ,最后执行 limit !!!