SQL初步学习

第一弹:

以下为表关系:

#1.查询选修“数据结构”这门课程的学生姓名

这里的表对应关系very复杂,所以我一开始选择使用嵌套语句

select studentName
from Student 
where studentNo in
(select studentNo 
from Score 
where courseNo in
(select courseNo
from Course
where CourseName='数据结构'));

这样有些弯弯绕绕,不如直接用连接语句。

select studentName
from Student,Score,Course
where Student.studentNo=Score.studentNo 
and Score.courseNo=Course.courseNo 
and courseName='数据结构';

#2.查询选修了课程编号为001和002的学生姓名、分数和课程号。

这里踩了坑,没看见Score表里就有courseNo,在Course表里苦苦挣扎,发现跑的太远了- -|

还有就是001和002不能连等,or之后要重写“什么=什么”;(还有这个分号,是english的)

select studentName,score,courseNo
From Student,Score
where Student.studentNo=Score.studentNo 
and Score.courseNo='001'or Score.courseNo='002';

#3.查询学过课程号为 001 但是没有学过课程号为 002 的课程的学生学号、 课程号和分数。

这里变化的只有“没学过002课程”的这个条件,这里我一开始选用在连接表查询下运用比较运算符<>不等于,查询出结果。如果在不连接初始表的情况下,关于两个表最终信息的查询我能做到的最简单代码如下。

select studentName,score,courseNo
From Student,Score
where Student.studentNo=Score.studentNo 
and Score.courseNo='001'
and Score.courseNo<>'002';

#4. 查询至少有一门课与学号为’1500001’的学生所学相同的学生的学号和姓名。

考察的应该是any,这里除去了1500001的情况。

select studentNo,studentName
from Student
where studentNo<>'1500001'and studentNo in
( select studentNo from Score where courseNo=any
(select courseNo from Score where studentNo='1500001')
);

 稍微改成连接两个需要的表,这样可以少写一个嵌套语句。BUT我在用join连接表时,系统在studentNo处反复报错,说studenNo不明确,应该是在join后的表中studentNo出现多次以至于无法定位。

select distinct studentNo,studentName
From Score inner join Student on Student.studentNo=Score.studentNo
where Score.studentNo <>'1500001' and courseNo =any
(select courseNo from Score where Score.studentNo='1500001');

#5.查询至少选修了学号为“0700001”学生所选修的所有课程的学生姓名。

这里把any改成all即可。

select studentNo,studentName
from Student
where studentNo<>'0700001'and studentNo in
( select studentNo from Score where courseNo =all
(select courseNo from Score where studentNo='1500001')
);
#6.查询本月过生日的学生信息。
这里要使用month函数。所有信息用*表示,我以11月为例。
select *
from Student
where month(birthday)=11;
这有前辈整理很全的日期函数,链接:
#7.查询没有成绩的学生信息。(使用 IN NOT IN 语句)
NOT IN语句
select *
from Student
where studentNo not in
(select studentNo from Score);

关于IN的方法,我觉得其实就是这样的,意义一样,即把空值找出来。

select *
from Student
left join Score on Student.studentNo=Score.studentNo
where score is null;

#8. 查询选修过课程的学生姓名。

select studentName
from Student
where studentNo in
(select studentNo from Score,Course where Score.courseNo=Course.courseNo);

TO BE CONTINUED——

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值