一:编写子查询:
查询学生“章涵”的班级编号,然后在学生表查询出与“章涵”的班级编号相同的学生编号、姓名、和班级编号
1)select ClassID from studentinfo where studentname="章涵";//查询学生“章涵”的班级编号
select id,name,ClassID from studentinfo where ClassID=(select ClassID from studentinfo where studentname="章涵");//查询与学生表某个学生的班级编号相同
2)select a.studentname from studentinfo a
inner join exam b
on a.id=b.studentid
inner join subject c
on c.id=b.subjectid
where c.subjectname="基于C语言理解软件编程" and b.score =90;
二:在UPDATE、DELETE、INSERT语句中使用子查询
1)UPDATE
UPDATE exam set score=55//全部成绩修改为55
where studentid=(//成绩修改为55的条件
select id from studentinfo where studentname="章涵"
and subjectid=(
select id from subject where subjectname="基于C语言理解软件编程"
))
2)DELETE
DELETE from exam where studentid=(
select id from studentinfo where studentname="章涵");
3)INSERT
INSERT 表名 select 字段列表 from 表名
三:高级子查询
1)IN/NOT IN
select a.studentname from studentinfo where id IN
(select studentid from exam where score=90//查询成绩为90的学生编号
and subjectid=
(select subjectid from subject where subjectname="基于C语言理解软件编程"))//查询“基于C语言理解软件编程”课程编号
select a.studentname from studentinfo where id NOT IN
(select studentid from exam where score=90
and subjectid=
(select subjectid from subject where subjectname="基于C语言理解软件编程"))//查询没有参加“基于C语言理解软件编程”
2)EXISTS/NOT EXISTS
select studentid,exam from exam where subjectid=2 and exists(select studentid from exam where exam<60);//先查询成绩不及格的id,若返回至少一行,则进行查询 成绩表中subjectid=2的id和成绩信息
select studentid,exam from exam where subjectid=2 and not exists(select studentid from exam where exam<60);//先查询成绩不及格的id,若无返回值,则进行查询
成绩表中subjectid=2的id和成绩信息
3)ALL、ANY、SOME
select * from exam where score > ALL(select score from exam where subjectid=1)//查询科目编号为1的这门课程的所有成绩都大的学生考试信息
select * from exam where score > ANY(select score from exam where subjectid=1)//查询科目编号为1的任意一个成绩都大的学生考试信息
select * from exam where score > SOME(select score from exam where subjectid=1)//查询科目编号为1的任意一个成绩都大的学生考试信息
原文地址:https://www.cnblogs.com/W19990605/p/11568582.html