教你使用SQL语句进行数据库复杂查询

时间:2023-04-27 11:19:11来源:互联网

下面小编就为大家分享一篇教你使用SQL语句进行数据库复杂查询,具有很好的参考价值,希望对大家有所帮助。

前言

本篇可当做例题练习,

1.查询比”林红”年纪大的男学生信息
语句:

select *
from Student
where Sex='男' and 
	year(Birth)-(select year(Birth)from Student--这里是需要告诉查询的表名,相当于嵌套
	where Sname='林红')<0

2.检索所有学生的选课信息,包括学号、姓名、课程名、成绩,性别.
语句:

select sc.sno,sname, course.Cno,Cname,Grade,Sex
--这里如果两个表中都有同一个属性,则需要标明在哪个表,如sc.sno
from student,sc,Course
where student.Sno=sc.Sno and Sc.Cno=course.Cno

3.查询已经选课的学生的学号、姓名、课程名、成绩.
语句:

select sc.sno ,sname , Cname , Grade
from student s , course c, sc
where s.sno=sc.sno and c.cno=sc.cno

(4)查询选修了“C语言程序设计”的学生的学号与姓名
–a.用内连接查询
语句:

select sc.Sno,sname from student inner join sc on
student.Sno=sc.Sno inner join course on sc.Cno =course.cno
and Cname='C语言程序设计'

–b.用连接查询
语句:

select sc.Sno,sname from student,sc,course where
student .Sno=sc.Sno and sc.Cno =course.cno
and Cname='C语言程序设计'

–c.用子查询
语句:

select Sno,sname from student where Sno in
(select Sno from sc where Cno=
(select cno from course where Cname ='C语言程序设计'))

(5)查询与”张虹”在同一个班级的学生学号、姓名、家庭住址
–a.用连接查询
语句:

select a.Sno,a.sname,a.Home_addr from student a,student b 
where a.Classno =b.Classno and b.Sname ='张虹' and a.Sname!='张虹'

–b.用子查询
语句:

select Sno,sname,Home_addr  from student where
classno=(select classno from student where sname='张虹')
and sname!='张虹'

(6)查询其他班级中比”051”班所有学生年龄大的学生的学号、姓名
代码1:

select Sno,sname,Home_addr  from student where
classno!='051' and Birth<all (select Birth  from student where classno='051')

代码2:

select Sno,sname,Home_addr  from student where
classno!='051' and Birth<(select min(Birth)  from student where classno='051')

(7)(选作)查询选修了全部课程的学生姓名。本题使用除运算的方法。
–由题意可得另一种语言,没有一个选了课的学生没有选course表里的课程。那么,我们需要两个NOT EXISTS表示双重否定;
语句:

select Sname from student
where not exists (
select * from course
where not exists (
select * from sc
where sno=student. sno
and cno=Course.cno))

(8)查询至少选修了学生“20110002”选修的全部课程的学生的学号,姓名。
语句:

select Sno, Sname from student
where sno in (
select distinct sno from sc as sc1
where not exists (
select * from sc as sc2 where sc2.sno='20110002'
and not exists (
select * from sc as sc3 where sc3.Sno=sc1.sno and
sc3.cno=sC2.cno) )
)

(9)检索选修了“高数”课且成绩至少高于选修课程号为“002"课程的学生的学号、课程号、成绩,并按成绩从高到低排列。
语句:

select sc.Sno, sc.cno , grade from sc where
grade >all(select grade from sc where cno='002' ) and
Cno= (select Cno
from course where Cname='高数')
order by Grade desc

(10)检索选修了至少3门

本站部分内容转载自互联网,如果有网站内容侵犯了您的权益,可直接联系我们删除,感谢支持!