交互式SQL—复杂查询(实验4-2)

嵌套查询和组合查询操作

#(1) 统计选修了【数据库原理】课程的学生人数。

select cno,count(sno) 
	from sc
		group by cno
			having cno in 
				(select cno from courses where cname='数据库原理');

#(2) 查询没有选修【数据库原理】课程的学生学号、姓名。

select sno,sname 
	from student 
		where sno not in
			(select sno from sc WHERE cno in
				(SELECT cno FROM courses where cname='数据可原理'));

#(3-1) 查询其他系中比计算机系学生年龄都小的学生学号、姓名和所在系。

   select student.sno,sname,sdep
   from student
     where sdep<>'计算机' and
       sbirthday>all(select sbirthday
         from student
           where sdep='计算机');

#(3-2) 查询其他系中比计算机系学生年龄都大的学生学号、姓名和所在系。

  select student.sno,sname,sdep
 	 from student
    	 where sdep<>'计算机' and
      		sbirthday<all(select sbirthday
         		from student
         		  where sdep='计算机');

#(4) 查询被0602001 学生或0602002 学生所选修的课程的课程号(用UNION 组合查询与IN 条件查询两种方法实现)。

(select distinct cno from sc where sno= '0602001')
	union
		(select distinct cno from sc where sno='0602002');

#or

select distinct cno 
	from sc 
		where sno in('0602001','0602002');

#(5) 查询0602001 学生和0602002 学生同时选修的课程的课程号(用IN 子查询与EXISTS 嵌套子查询两种方法实现)。

select  cno from sc where sno= '0602001'
	and cno in
		(select  cno from sc where sno= '0602002');

#or

select cno 
	from sc sc1
		where sno='0602001'
      		and exists(SELECT * from sc sc2 where sc1.cno=sc2.cno and 
  				sc2.sno='0602002');

#(6) 查询被学号0602001 学生选修,但没有被0602002 学生所选修的课程的课程号。

select  cno 	
	from sc 
		where sno= '0602001'
			and cno not in
				(select  cno from sc where sno= '0602002');

猜你喜欢

转载自blog.csdn.net/YZ_TONGXIE/article/details/106805405
4-2