连接查询和子查询

连接查询

查询学号为“s5”的学生的选课信息,要求列出学号,姓名,课程号和课程名称。

select s.sno,s.sn,c.cno,c.cn

from s,c,sc

where s.sno=sc.sno and c.cno=sc.cno and s.sno='s5';

查询所有授课教师的教师号、姓名和讲授的课程,并且按照教师号升序排列。

select t.tno,tn,cn

from t,c,tc

where t.tno=tc.tno and c.cno=tc.cno

order by tno;

 

查询选课人数在3人及以上的课程号、课程名和选课人数。

select c.cno,cn,count(sno)

from c,sc

where c.cno=sc.cno

group by c.cno

having count(sno)>=3;

 

查询没有选课的学生信息。

select *

from s left join sc

on s.sno=sc.sno

where cno is null;

 

查询没有学生选课的课程信息。

select *

from c left join sc

on c.cno=sc.cno

where sno is null;

 

查询和“王彤”在同一个系的学生的姓名。

select y.sn

from s as x,s as y

where x.dept=y.dept and x.sn='王彤';

 

查询和“程序设计基础”课程课时数相同的其他课程信息。

select y.*

from c as x,c as y

where x.ct=y.ct and x.cn='程序设计基础';

 

不相关子查询

(一)使用带IN谓词的子查询

(1) 查询与’苏乐’在同一个专业学习的学生的信息。

select *

from s

where maj in (select nmaj 

                     from update_s_log 

                     where sn='苏乐');

 

    比较:in、=、连接查询的结果

 

查询选修了课程名为’数据库系统’ 的学生的学号和姓名。

select sno,sn

from s

where sno in (select sno 

                     from sc 

                     where cno in(select cno 

                                         from c 

                                         where cn='数据库系统'));

       

查询教师号为“t1”的教师讲授的课程的课程号、课程名和课时。

 

select cno,cn,ct

from c

where cno in (select cno 

                       from tc 

                       where tno='t1');

 

(二) 使用带比较运算的子查询

 (4) 查询比’王彤’年龄小的所有学生的信息。

select *

from s

where age<(select age 

                   from s 

                   where sn='王彤');

 

查询与教师“顾伟”职称不同的教师的教师号、姓名和职称。

select tno,tn,prof

from t

where prof<>(select prof 

                     from t 

                    where tn='顾伟');

 

(三)带Any, All谓词的子查询(min()和max()函数的使用)

(6)查询其他院系中比信息学院某一学生年龄大的学生姓名和年龄。

 

select sn,age

from s

where age>any(select min(age) 

                         from s 

                        where dept='信息学院');

 

(7)查询其他院系中比信息学院学生年龄都大的学生姓名和年龄。

select sn,age

from s

where age>any(select max(age)

                          from s

                         where dept='信息学院');

 

相关子查询(带Exists谓词的子查询)

查询所有选修了“c1”课程的学生姓名。

select sn

from s

where exists (select *

                     from sc

                     where s.sno=sc.sno and cno='c1');

 

      (9)查询没有选修了“c1”号课程的学生姓名。

select sn

from s

where not exists (select *

                           from sc

                           where s.sno=sc.sno and cno='c1');

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值