MySQl数据库DQL操作
数据的查询,在数据库中非常重要
- 简单查询
- 关系查询
- 子查询
- 集合查询
简单查询
select 查询
select expr;
-- 简单计算
select 1+2;
-- 查询当前系统时间;
select now();
-- 查询当前用户;
select user();
-- 查询数据库的版本;
select version();
from 查询
select 查询的字段列表 from 表,表1,....;
ps:查询的字段列表 多个字段,用 逗号 分割,如果表中所有字段,可以用 * 来标识,但不推荐使用
where 查询
对数据库中的数据进行筛选
select 查询的字段列表 from 表名 where 条件;
where 中常见的查询条件
- 关系查询 > , >= , < , <= , = , != ,<>(不等于)
-- 查询姓名是张三的学生信息
select * from t_student where name = '张三';
-- 查询 出生日期 大于等于 1995-03-01 的所有学生名称
select name from t_student where birth >= '1995-03-01';
- 逻辑查询
-- 查询 姓名为张三且性别为男的学生信息
select * from t_student where name = '张三' and sex = '男' ;
-- 查询 姓名张三 或者出生日期是 1990-05-01的学生信息
select * from t_student where name = '张三' and birth = '1990-05-01' ;
- 区间查询 between…and…
-- 查询 出生日期在 1995-01-01 ---- 2000-01-01 之间的所有学生信息
select * from t_student where birth between '1995-01-01' and '2000-01-01' ;
- 枚举查询 in ( 条件 )
查询 张三、李四、王五、赵六 的学生信息
select * from t_student where name in ('张三','李四,'王五','赵六' )
- 模糊查询 like
符号 | 含义 |
---|---|
% | 匹配 0-N个字符 |
_ | 只能匹配一个字符 |
-- 查询 姓张的所有学生信息
select * from t_student where name like = '张%'
-- 查询 姓名中包含 四 的学生信息
select * from t_student where name like '%四%' ;
-- 查询 姓名 以 四 结尾的学生信息
select * from t_student where name like '%四' ;
-- 查询 姓张 且名字长度为2 的学生信息
select * from t_student where name like '张_'
```sql
- 空值查询 is null / is not null
– 查询身份证号为 空 的学生信息
select * from t_student where cardNo is null;
### 分组查询 group by
group by 分组一般和 聚合函数配合使用,完成数据的查询
```sql
常见的聚合函数有:
count:统计个数
max:求最大值
min:求最小值
max:求最大值
sum:求和
avg:求平均值
PS : 空值不参与聚合
group by 对查询的列的要求
查询的列出现在 group by 的后面, 或者 出现在聚合函数中
-- 查询 班级中 男生、女生各有多少人
select sex , count(sex) from t_student group by sex ;
-- 查询 男生、女生 年龄最大的 学生名字
select name from t_student t where exists (
select a.* from
(select f.sex, min(f.birth) as minbirth from t_student f group by f.sex) a
where t.sex = a.sex and t.birth = a.minbirth
)
having 子句
- having 不能单独使用,必须配合 group by 完成对分组的结果进行筛选
PS:
where: 对数据库的记录进行筛选, where 比 having 先执行
having:对分组后的结果进行筛选, 能用where筛选数据的不要使用having筛选、、
查询 同名、同性的所有学生名字
select name from t_student group by sex , name having count(1) > 1;
order by
对查询的结果进行排序、执行顺序在 select 之后
- ASC : 升序排列,默认值
- DESC: 降序排列
order by 排序字段 【排序规则】
分页查询 limit
limit [offset, ] rows
offset : 偏移量,默认从0开始
rows : 每页显示的条数
page: 页码
offset = (page -1) * rows ;