数据库-sql语法例子

例子:对于教学数据库中的四个关系:
教师关系 T(t#,tname,title)
课程关系 C(c#,cname,t#)
学生关系 S(s#,sname,age,sex)
选课关系 SC(s#,c#,score)
①检索学习课程号为C2课程的学生学号与姓名。
<1>select s.s#,sname from S,SC where S.s#=SC.s# and c#=c2;
<2>select s#,sname from S where s# in(select s# from SC where c#='c2');//嵌套查询
<3>select s#,sname from S where exists(select * from SC where SC.s#=S.s# and c='c2');//使用存在量词的嵌套查询
②检索至少选修liu老师所授课程的学生学号与姓名
<1>select S#,sname from S,SC,T,C where S.s#SC.s# and SC.c#=C.c# and C.t#=T.t# and Tname='liu';
<2>select S.s#,sname from S where S.s# in(select S.s# from SC where c# in(select c# from C where t# in(select t# from T where Tname='liu') ));
③检索选修课程号为C2或C4的学生学号
select s# from SC where c#='c2' or c#='c4';
④检索至少选修课程号为C2和C4的学生学号
select X.s from SC X,SC Y where X.s#=Y.s# and X.c#='c2' and c#='c4'//同一个基本表SC在同一层出现了量词,变量X和Y加以限定。
⑤检索不学c2课程的学生姓名与年龄
select sname,age from S where s# not in(select s# from SC where c#='c2')
⑥检索学习全部课程的学生姓名
select sname from S where not exists(select * from C where not exists * from SC where SC.S# and SC.c#=C.c#)
⑦求男学生的总人数和平均年龄
select count(*),avg(avg) from S where sex='M'
⑧统计每门课程的学生选修人数,要求显示课程号、课程名和学生人数。
select C.c#,cname,count(s#) from SC,C where SC.c#=C.c# group by C.c#,cname;//分组之后(C.c#,cname)只有一个值,则统计的s#个数就是这组学生的学生人数。
⑨求每一教师每门课程的学生选修人数(超过50人),要求显示教师工号、课程号和学生人数。显示时,查询结果按人数升序排列,人数相同按工号升序、课程号降序排列。
select C.t#,C.c#,count(s#) from SC,C where C.c#=SC.c# group by t#,C.c# having count(*)>50 order by 3,T#,C.c# DESC;//根据教师工号和课程号分组,使用having组条件子句选取满足条件的子句,3表示对select子句中第3个属性值(学生人数)进行升序排列,若人数相同,按工号升序、课程号降序。
⑩在基本表SC中检索男同学选修的课程的课程号。
select distinct c# from S,SC where S.s#=SC.s# and sex='M';//避免输出重复的课程号,因此加上distinct
⑪在基本表S中检索每个学生的姓名和出生年份,输出的列名为student_name和birth_year.
.select sname as student_name,2017-age as birth_year from S;

;⑬;⑭;⑮;⑯;⑰;⑱;⑲;⑳

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值