MySQL学习笔记-DQL
去重 distinct
作用:去除select查询出来的结果中重复的数据,并重复的数据只显示一条
select distinct id from student; -- 重复数据可去重
数据库的列(表达式)
select version() -- 查询系统版本(函数)
select 1+1 as result -- 计算 (表达式)
select @@auto_increment_increment -- 查询自增的步长 (变量)
数据库中的表达式:文本值,列,null,函数,计算表达式,系统变量…
select 表达式 from 表
模糊查询:比较运算符
运算符 | 语法 | 描述 |
---|---|---|
is null | a is null | 如果操作符为null,结果为真 |
is not null | a is not null | 如果操作符不为null,结果为真 |
between | a between b and c | 若a在b和c之间,则结果为真 |
like | a like b | SQL匹配,如果a匹配b,则结果为真 |
in | a in (a1,a2,a3…) | 假设a在a1,或者a2…其中的某一个值,结果为真 |
-- 查询姓李的用户,名字后面只有一个字的
select username from user where username like '李_'
-- 查询姓李的用户,名字后面只有任意个字的
select username from user where username like '李%'
-- 查询名字中带有木子的用户
select username from user where username like '%木%'
联表查询
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gmYPBVLG-1621230167906)(C:\Users\10098\AppData\Roaming\Typora\typora-user-images\image-20210509100617393.png)]
操作 | 描述 |
---|---|
inner join | 如果表中至少有一个匹配,则返回行 |
left join | 会从左表中返回所有的值,即使右表中没有匹配 |
right join | 会从右表中返回所有的值,即使左表中没有匹配 |
- join (连接的表) on (判断的条件) 连接查询
- where 等值查询
查询时思路:
- 分析需求,分析查询的字段来源于哪张表
- 确定使用哪种连接查询
- 确定交叉点(即此两张表中哪些数据是相同或是有关联的)
- 判断的条件
select s.studentNo,studentName,subjectName,studentResult
from student as s
right join result as r
on s.studentNo = r.studentNo
inner join `subject` as sub
on r.subjectNo = sub.subjectNo;
自连接
即自己的表与自己的表连接,核心:一张表拆位两张一样的表
select a.categoryName as '父名称', b.categoryName as '子名称'
from category as a , category as b
where a.categoryId = b.pid;
分页和排序
- 排序
- 升序 asc
- 降序 desc
order by 通过哪个字段排序,按什么方式排序
select studentName,score from student order by score desc; -- 根据成绩降序排序
- 分页
- 缓解数据库压力
- 给人的体验更好
limit 起始值,页面大小
select *from student limit 0,5;
-- 第一页 limit 0,5 (1 - 1) * 5
-- 第二页 limit 5,5 (2 - 1) * 5
-- ...
-- 第N页 limit (N - 1) * 5,5 (N - 1) * 5
-- [pageSize:页面大小]
-- [(n - 1) * pageSize:起始值]
-- [n:当前页]
-- [数据总页 / 页面大小] = 总页数
select s.studentNo,studentName,subjectName,studentResult
from student as s
right join result as r
on s.studentNo = r.studentNo
inner join subject as sub
on r.subjectNo = sub.subjectNo
where subjectName = 'Java程序设计-1'
and studentResult > 80
order by studentResult desc
limit 0,10
子查询
where(此值为计算出来的)
本质:在where语句中嵌套一个子查询语句
-- 查询:数据库课程中所有考试结果(学号,科目编号,成绩),降序排列
select studentNo,subjectNo,studentResult
from result
where subjectNo = (
select subjectNo from `subject`
where subjectName = '数据库'
)
order by studentResult desc
-- 由里即外