5.SQL--查询"01"课程比"02"课程成绩高的学生的信息及课程分数

--以本例子为例,先介绍下几种常用的表连接,本例只用到left join,其它自己可尝试----测试下:
--inner join 内连接,结果是两个表都包含Sid的行;
--left join 左连接,结果是以左表的Sid为准,右表没有的为空值null
--right join 右连接,结果是以右表的Sid为准,左表没有的为空值null
--full outer join 全外连接,结果是包含二表数据

例子:查询"01"课程比"02"课程成绩高的学生的信息及课程分数
--1、第一种方法:左连接,查询同时存在'01'课程和'02'课程的学生信息,然后再进行---比较, isnull用法,如果score有值则返回score,如果score为null则返回0
select a.*,b.score [课程'01'的分数],c.score [课程'02'的分数] from Student a
left join SC b on a.Sid=b.Sid and b.Cid='01'
left join SC c on a.Sid=c.Sid and c.Cid='02'
where b.score>isnull(c.score,0)

--2、第二种写法
select a.* , b.score [课程'01'的分数],c.score [课程'02'的分数] from Student a , SC b , SC c
where a.Sid = b.Sid and a.Sid = c.Sid and b.Cid = '01' and c.Cid = '02' and b.score > c.score

猜你喜欢

转载自blog.51cto.com/12679593/2396109