数据库多表查询

--多表查询
--查询选修了课程名为“信息系统”的学生学号和姓名
select sno,sname
from student
where sno in(
select sno
from course,sc
where cname='信息系统' and
		course.cno = sc.cno);

--或者
select sno,sname
from student
where sno in(
	select sno
	from sc
	where cno in(
		select cno
		from course
		where cname='信息系统'));

--或者
select student.sno,sname  --由于student和sc里面均有sno,所以需要指明是哪个表里面的sno
from student,sc,course
where student.sno=sc.sno and  --进行连接的时候一定要说明连接的列
		course.cno = sc.cno and
		cname='信息系统';

--或者
select student.sno,sname
from student,sc
where cno in(
	select cno
	from course
	where cname='信息系统' ) and
	student.sno = sc.sno;
	
	
--找出每个学生超过他选修课程平均成绩的课程号。
select sno,cno
from sc x  --x和y均为别名
where grade>=
	(select avg(grade)
	from sc y
	where x.sno = y.sno);  --为什么不需要distinct???


--查询其他系中比信息系任意一个(其中某一个)学生年龄小的学生姓名和年龄
select sname,sage
from student
where sage<any
		(select sage
		from student
		where sdept='IS')and 
		sdept!='IS';
		
--查询所有选修了1号课程的学生姓名。
select sname
from student,sc
where student.sno=sc.sno and
	student.sno in
	(select sc.sno
	from sc
	where cno=1
	);
	
--或者
select sname
from student
where exists
	(select *
	from sc
	where student.sno=sc.sno and
	cno=1);
	
----查询没有选修了1号课程的学生姓名。
select sname
from student
where not exists
	(select *
	from sc
	where student.sno=sc.sno and
	cno=1);
	
--查询与“刘晨”在同一个系学习的学生。
select sno,sname
from student x
where exists
	(select *
	from student y
	where x.sdept=y.sdept and
	y.sname='刘晨'
	);
--查询选修了全部课程的学生姓名  没有一门课是他不选的  比较的是集合,而集合是DBMS在底层实现的
select sname
from student
where not exists  --没有一门课
	(select *
	from course
	where not exists  --没选
	(select *
	from sc
	where sno = student.sno and  --比较的是这门课该学生有没有选
	cno = course.cno));
	
	
--查询至少选修了学生201215122选修的全部课 程的学生号码。  不存在这样的课程y,学生201215122选修了y,而学生x没有选
select distinct sno
from sc  x
where not exists  --不存在课程
	(select *
	from sc y
	where y.sno=21 and
	not exists
	(select *
	from sc z
	where x.sno=z.sno and
		z.cno=y.cno));
		
		
--查询计算机科学系的学生及年龄不大于19岁的学生
select sno
from student
where sdept='CS'
union
select sno
from student
where sage<=19
order by sno;--order by语句一定是在最后

--或者
select sno
from student
where sdept='CS' or
	sage<=19;
	
	
--查询计算机科学系的学生与年龄不大于19岁的学生的交集(INTERSECT) 。
select sno
from student
where sdept='CS'
intersect
select sno
from student
where sage<=19;

--或者
select sno
from student
where sdept='CS' and
	sage>19;
	
	
	
--查询计算机科学系的学生与年龄不大于19岁的学生的差集。
select sno
from student
where sdept='CS'
except
select sno
from student
where sage<=19;

--或者
select sno
from student
where sdept='CS' and
	sage>19;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值