--单关系表的查询
--无条件查询
select distinct SNo from SC
--条件查询
--比较大小
select SNo,Score from SC where CNo='C1'
--多重条件查询
select SNo,CNo,Score from SC
where (CNo='C1' or CNo='C2') and Score>=85
--确定范围
select TNo,TN,Prof from T
where Sal not between 1000 and 1500
--确定集合
select SNo,CNo,Score from SC
where CNo not in ('C1','C2')
--部分匹配查询
select TNo,TN from T where TN like '张%'
select TNo,TN from T where TN like '_力%'
--空值查询
select SNo,CNo from SC where Score is null
--常用库函数及统计汇总查询
--SUM和AVG函数
select sum(Score) as TotalScore,avg(Score) as AvgScore
from SC where SNo='S1'
--MAX和MIN函数
select max(Score) as MaxScore,min(Score) as MinScore,
max(Score)-min(Score) as diff from SC where SNo='S1'
--COUNT函数
select count(distinct Dept) as DeptNum from S
--分组查询
--查询选修两门以上课程的学生的学号和选课门数
select SNo,count(*) as C_Num from SC
group by SNo having(count(*)>=2)
--查询结果的排序
--查询结果按学号升序排列,学号相同再按成绩降序排列
select SNo,Cno,Score from SC
where CNo in ('C2','C3','C4','C5')
order by SNo,Score desc
--多关系表的查询
--内连接查询
--查询"刘伟"老师所讲授的课程,列出教师号、教师名和课程号
--方法1
select T.TNO,TN,CNo from T,TC
where (T.TNO=TC.tNo) and TN='刘伟'
--方法2
select T.TNO,TN,CNo from T inner join TC
on T.TNO=TC.tNo where TN='刘伟'
--方法3
select R1.TNO,R2.TN,R1.CNo
from (select TNo,CNo from TC) as R1
inner join
(select TNo,TN from T where TN='刘伟') as R2
on R1.tNo=R2.TNO
--查询每门课程的课程号、课程名和选课人数
select C.CNo,CN,count(SC.SNo) as 选课人数
from C,SC where SC.cNo=C.CNo
group by C.CNo,CN
--外连接查询
--查询所有学生的学号、姓名、选课名称和成绩(没有选课同学显示为空)
select S.SNo,SN,CN,Score from S
left outer join SC on S.SNo=SC.sNo
left outer join C on C.CNo=SC.cNo
--交叉连接
select * from S cross join C
--自连接查询
--查询所有比"刘伟"工资高的教师姓名、工资和刘伟的工资
--方法1
select X.TN,X.Sal AS Sal_a,Y.Sal AS Sal_b
from T as X,T as Y
where X.Sal>Y.Sal and Y.TN='刘伟'
--方法2
select X.TN,X.Sal,Y.Sal
from T as X inner join T as Y
on X.Sal>Y.Sal and Y.TN='刘伟'
--方法3
select R1.TN,R1.Sal,R2.Sal
from
(select TN,Sal from T) as R1
inner join
(select Sal from T where TN='刘伟') as R2
on R1.Sal>R2.Sal
--检索所有学生姓名、年龄和选课名称
--方法1
select SN,Age,CN from S,C,SC
where S.SNo=SC.sNo and SC.cNo=C.CNo
--方法2
select R3.SN,R3.Age,R4.CN
from
(select SNo,SN,Age from S) as R3
inner join
(select R2.SNo,R1.CN
from
(select CNo,CN from C) as R1
inner join
(select SNo,CNo from SC) as R2
on R1.CNo=R2.cNo)
as R4
on R3.SNo=R4.sNo