多表查询 连接 A join B on A.x =B.y 外连接 left join right join
where 后面嵌套 in
存在 exists
exists(查询是否有记录) 可以替代所有 in 连接
关系代数 并 union or 交 and 差 not 笛卡儿积
已知
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
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))