【数据库】连接、嵌套、关系代数

【数据库】连接、嵌套

多表查询 连接 A join B  on A.x =B.y  外连接 left join  right join
where 后面嵌套 in   
存在 exists
 exists(查询是否有记录) 可以替代所有 in 连接
 关系代数  并 union orandnot  笛卡儿积   

已知
Student(Sno,Sname,Ssex,Sage,Sdept)
Course(Cno,Cname,Ccredit,Cpno)
SC(Sno,Cno,Grade)

  • 选修了全部课程的学生(逆否命题 :不存在课程这个学生不选)
select * from Student where not exists(select * from Course where not exists(select
* from SC where Sno = Student.Sno and Cno=Course.Cno))
  • 查询每个学生的姓名以及榜样(本系平均成绩最好的同学) 以及和榜样的差距
select (select Sname from Student where Sno=t.Sno) as Sname,
(select Sname from Student where Sno=t.BSno) as Bname,
(select avg(Grade) from SC where Sno=t.Bsno) -(select avg(Grade) from SC where Sno=t.Sno) 
as 差距
 from (
select Sno,( select top 1 Sno from SC where 
Sno in (select Sno from Student where Sdept = s.Sdept) group by Sno 
order by avg(Grade) desc ) as BSno from Student as s ) as t
  • 查询学生 姓名 课程 和 成绩
(select Cname from Course where Cno = SC.Cno) as Cname,Grade  from SC 

-- or
select Sname,Cname,Grade from Student right join SC on Student.Sno=SC.Sno right 
join Course on SC.Cno = Course.Cno
  • 查询 课程号 课程名 先序课程名 学分最大的后序课程
 select s1.Cno,s1.Cname,s2.Cname,s3.Cname from Course as s1 left join Course as s2 on 
  s1.Cpno = s2.Cno join Course as s3 on s1.Cno = s3.Cpno
  • not in 和 exist
select * from Student where  not Sno in (select Sno from SC)
select * from Student where not exists(select * from SC where Sno=Student.Sno)
  • 以刘晨为榜样 查询和刘晨在同一个系,并且选修了刘晨所选修全部课程并且成绩为优秀的 学生姓名(逆否:不存在课程 刘晨选了 这个学生没选)
select * from Student where not exists(select * from Course where 
exists(select * from SC where Sno in (select Sno from Student where Sname='刘晨') and Cno=
Course.Cno) and not exists (select * from SC where Sno=Student.Sno and Cno=Course.Cno)) 
and Sdept = (select Sdept from Student where Sname='刘晨') 
  • 统计人数最多系的平均分
select Sdept, avg(Grade) from
(select Sno,Cno,Grade,(select Sdept from Student where Sno=SC.Sno) as Sdept from SC ) as t
group by Sdept 
having Sdept in (select top 1 Sdept from Student group by Sdept order by  count(*) desc)
  • 并示例
select Sname,Sage from Student union select Tname,Tage from Teacher 
  • 选修了全部课程且成绩均为优秀的学生
    逆否命题:
    不存在课程 这个学生选了成绩不优秀 或者没选
    不存在课程 这个学生不以优秀成绩来选
select * from Student where not exists(select * from Course 
where (exists(select * from SC where Sno=Student.Sno and Cno=Course.Cno and Grade<90)) or
not exists (select * from SC where Sno=Student.Sno and Cno=Course.Cno))

select * from Student where not exists(select * from Course 
where (not exists(select * from SC where Sno=Student.Sno and Cno=Course.Cno and Grade>=90))

你可能感兴趣的:(数据库)