面试常见查询语句(能掌握以下几个例子就基本可以了)

  1. 云栖社区>
  2. 博客>
  3. 正文

面试常见查询语句(能掌握以下几个例子就基本可以了)

yexx 2017-02-12 16:25:00 浏览1086
展开阅读全文

表结构:
student(s#,sname,sage,ssex)学生表
course(c#,cname,T#)课程表
sc(s#,c#,score)成绩表
Teacher(T#,tname)教师表

1.查询001课程比002课程成绩高的所有学生的学号:
select sc1.s#
from sc sc1 join sc sc2 on sc1.s# = sc2.s#
where sc1.c# = ‘001’ and sc2.c# = ‘002’ and sc1.score > sc2.score

2.查询平均成绩大于60分的同学的学号和平均成绩:
select s#, avg(score) from sc group by s# having avg(score)>60;

3.查询所有同学的学号,姓名,选课数,总成绩:
select student.s#,student.name ,count(sc.c#) ,sum(sc.score)
from student left join sc on student.s# = sc.s# 注:内连接要计算笛卡尔积,这里使用左外连接效率更高

4.查询姓李的老师个数:
select count(T#) from Teacher where tname like “李%”
注:模糊查询, %代表任意字符,_代表任一单个字符,[……]代表是括号中字符中的单个字符, [^……]代表不是括号中字符中的单个字符

5.查询没有学过叶萍老师课的同学学号,姓名:
select studet.s# student.sname
from student
where s# not in (select distinct(sc.s#) from sc, course, teacher where sc.c# = course.c# and teacher.t# = course.t# and teacher.tname = “叶萍”);
三表联合 + 子查询

6.查询学过001和002课程的同学的姓名学号:
select student.s3 student .sname
from student join course on student.s# = course.s#
where(course.c# = ‘001’ union course.c# = ‘002’);

7.查询学过叶萍老师课的同学的学号,姓名:
select student.s# student.sname
from student
where s# in(select distinct(sc.s#) from sc course teacher where sc.c# = course.c# and teacher.t# = course.t# and teacher.tnmae = “叶萍”) 注:distinct为去重函数

8.查询002成绩比001低的同学的学号,姓名:
select student.s# student .name
from student where student.s# in(select sc1.s# from sc sc1 join sc sc2 on sc1.s# = sc2.s# where s1.c# = 001 and s2.c# = 002 and sc1.score> sc2.score);

9.查询所有课程成绩小于60分的同学的学号,姓名:
select student.s# student.sname from student join sc on student.s# = sc.s#
where sc.score > 60;

10.查询没有学全 所有课的同学的学号和姓名:
select student.s# student.sname from student,sc
where student.s# = sc.s# group by student.s#,student.sname having count(c#) < (select count(c#)from course);

11.查询至少有一门课程与学号1001的同学所学相同的同学的学号和姓名:
select student.s# ,student.sname from student join sc
where student.s# = sc.s# and c# in select c# from sc where s# = ‘1001’

12.查询至少学过学号为001同学所有一门课的其他同学的学号和姓名:
select distinct student.s#,student,sname from
SC join student on SC.s# = student.s#
where c# in(select c# from sc where s#=’001’);

网友评论

登录后评论
0/500
评论
yexx
+ 关注