select语法
排序
排序:升序 asc 降序 desc
order by 通过哪个字段排序,怎么排
-- 排序:升序 asc 降序 desc
-- order by 通过哪个字段排序,怎么排
-- 查询参加 数据库结构-1 考试的同学信息:学号,学生姓名,科目名,分数
-- 查询的结果根据 成绩降序排序
SELECT s.`studentno`,`studentname`,`subjectname`,`studentresult`
FROM `student` AS s
INNER JOIN `result` r
ON s.`studentno`=r.`studentno`
INNER JOIN `subject` sub
ON r.`subjectno`=sub.`subjectno`
WHERE `subjectname`="数据库结构-1"
ORDER BY `studentresult` DESC
分页
语法 limit 起始值,页面的大小
-- 为什么要分页
-- 缓解数据库压力,给人更好的体验
-- 如果不分页就是瀑布流(类似于抖音)
-- 分页 每页只显示5条数据
-- 语法 limit 起始值,页面的大小
SELECT s.`studentno`,`studentname`,`subjectname`,`studentresult`
FROM `student` AS s
INNER JOIN `result` r
ON s.`studentno`=r.`studentno`
INNER JOIN `subject` sub
ON r.`subjectno`=sub.`subjectno`
WHERE `subjectname`="数据库结构-1"
ORDER BY `studentresult` DESC
LIMIT 0,5
-- 第一页 limit 0,5 (1-1)*5,5
-- 第二页 limit 5,10 (2-1)*5,5
-- 第n页 limit (n-1)*pagesize,pagesize(页面大小)
-- 数据总数/页面大小 = 总页数
-- 思考
-- 查询 Java程序设计-1 课程排名前5的学生,并且分数要大于80的学生信息
-- (学号,姓名,课程名.分数)
SELECT s.`studentno`,`studentname`,`subjectname`,`studentresult`
FROM `student` AS s
INNER JOIN `result` AS r
ON s.`studentno`=r.`studentno`
INNER JOIN `subject` AS sub
ON sub.`subjectno`=r.`subjectno`
WHERE `studentresult` > 80 AND `subjectname` = "Java程序设计-1"
ORDER BY `studentresult` DESC
LIMIT 0,10
子查询
-- 1. 查询 数据库结构-1 的所有考试结构(学号,科目名,成绩),按成绩降序排列
-- 方式1.使用连接查询
SELECT `studentno`,`subjectname`,`studentresult`
FROM `result` AS r
INNER JOIN `subject` AS sub
ON r.`subjectno`=sub.`subjectno`
WHERE `subjectname`="数据库结构-1"
ORDER BY `studentresult` DESC
-- 方式2.使用子查询
-- 方式2.使用子查询
SELECT `studentno`,`subjectno`,`studentresult`
FROM `result`
WHERE `subjectno` =(
SELECT `subjectno` FROM `subject` WHERE `subjectname`="数据库结构-1"
)
ORDER BY `studentresult` DESC
-- 查询数据库结构-1分数不小于80的学生的学号和姓名 方式1:级联查询
SELECT DISTINCT s.`studentno`,`studentname`
FROM `student` AS s
INNER JOIN `result` AS r
ON s.`studentno`=r.`studentno`
INNER JOIN `subject` AS sub
ON sub.`subjectno`=r.`subjectno`
WHERE `studentresult`>=80 AND `subjectname` = "数据库结构-1"
-- 方式2 子查询
SELECT DISTINCT s.`studentno`,`studentname`
FROM `student` AS s
INNER JOIN `result` AS r
ON s.`studentno`=r.`studentno`
WHERE `studentresult`>=80 AND `subjectno`=(
SELECT `subjectno` FROM `subject`
WHERE `subjectname` = "数据库结构-1"
)
嵌套查询
-- 方式3 嵌套查询(由里及外)
SELECT `studentno`,`studentname` FROM `student` WHERE `studentno`
IN (
SELECT `studentno` FROM `result` WHERE `studentresult`>=80 AND
`subjectno` IN (SELECT `subjectno` FROM `subject` WHERE `subjectname` = "数据库结构-1")
)