您的位置:首页 > 数据库 > MySQL

MySQL经典练习题(五)

2020-07-07 20:45 330 查看

 题目:5. 查询「李」姓老师的数量

模糊查询

[code]select count(*) from teacher where tname like '李%';

结果:

题目:6.查询学过「张三」老师授课的同学的信息

第一种:# 先查tid,再查cid,再查sid,最后学生信息

[code]select * from student as st
where st.sid in
(select sc.sid from scores as sc
where sc.cid in
(select co.cid from course as co
where co.tid in
(select te.tid from teacher as te
where tname = '张三')));

结果:

第二种:

笛卡尔积结合多个表,再筛选

[code]select * from student where sid in (
select sid from scores as sc, course, teacher
where sc.cid = course.cid
and course.tid = teacher.tid
and tname = '张三'
);

题目:7. 查询没有学全所有课程的同学的信息

直接写即可

[code]select * from student
where sid
in
(select sid
from scores
group by sid
having count(cid) < 3);

结果:

题目:8. 查询和" 01 "号的同学学习的课程完全相同的其他同学的信息

参考其他,虽然写出来了,但是有点取巧的意思。因为如果有4门课程,01只选了3门,而有人选了

其他3门。再用having >=3 就不行了。(后续自己再想想)

[code]select * from student
where sid in(
select sid from scores
where cid in (select cid from scores where sid = '01') and Sid <>'01'
group by sid
having count(cid)>=3
);

结果:

题目:9. 查询至少有一门课与学号为" 01 "的同学所学相同的同学的信息

1、首先,查01学的所有课程

[code]select cid from scores where sid = '01';

结果:

2、然后,查有一门和01一样的学生

[code]select sid from scores
where cid in
(select cid from scores where sid='01') and sid<>'01'
group by sid;

结果:

3、最后,查信息

[code]select * from student
where sid in
(select sid from scores
where cid in
(select cid from scores where sid='01') and sid<>'01'
group by sid);

结果:

题目:10. 查询没学过"张三"老师讲授的任一门课程的学生姓名

1、首先,查张三的tid

[code]select tid from teacher
where tname = '张三';

结果:

2、 根据tid查cid

[code]select cid from course
where tid in
(select tid from teacher
where tname = '张三');

结果:

3、根据cid查上过这课的sid

[code]select sid from scores
where cid in
(select cid from course
where tid in
(select tid from teacher
where tname = '张三'));

结果:

4、最后,根据上过这个课的sid,查未上过该课的学生名单

[code]select sname from student
where sid not in
(select sid from scores
where cid in
(select cid from course
where tid in
(select tid from teacher
where tname = '张三')));

结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: