where (计算出的值)
本质: 在where语句中嵌套一个子查询语句
代码演示:
sql
-- 1. 查询数据库结构-1 的所有考试结果(学号,科目名称,成绩),降序排列
-- 方式一:使用连接查询
SELECT studentno,subjectname,studentresult
FROM result r
INNER JOIN `subject` sub
ON r.subjectno = sub.subjectno
WHERE subjectname = '数据库结构-1'
ORDER BY studentresult DESC
-- 方式二:使用子查询(由里及外)
SELECT studentno,subjectno,studentresult
FROM result
WHERE subjectno = (
SELECT subjectno FROM `subject` WHERE subjectname = '数据库结构-1' -- 查询所有数据库结构-1 的学生学号
)
ORDER BY studentresult DESC
-- 2. 分数不小于80分的学生的学号和姓名
SELECT DISTINCT s.studentno,studentname -- DISTINCT:去重
FROM student s
INNER JOIN result r
ON r.studentno = s.studentno
WHERE studentresult>=80
-- 在此基础上增加一个科目
SELECT DISTINCT s.studentno,studentname -- DISTINCT:去重
FROM student s
INNER JOIN result r
ON r.studentno = s.studentno
WHERE studentresult>=80 AND subjectno = (
SELECT subjectno FROM `subject` WHERE subjectname = '高等数学-1'
)
-- 再改造(由里及外)
SELECT studentno,studentname FROM student WHERE studentno IN (
SELECT studentno FROM result WHERE studentresult>=80 AND subjectno = (
SELECT subjectno FROM `subject` WHERE subjectname = '高等数学-1'
)
)