1. 程式人生 > >面試常見查詢語句(能掌握這幾個例子就可以了)

面試常見查詢語句(能掌握這幾個例子就可以了)

摘要: 表結構: 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

相關資料:
1、《經典書籍Head First PHP&MySQL》,關鍵詞“mysql書籍”。
2、一篇文章(包含程式碼)讓你掌握mysql的使用,關鍵詞“mysql”。領取辦法:關注“大資料研習社”後(掃描頭像二維碼即可關注),微信後臺回覆對應關鍵詞,即可獲得私密下載連結。

表結構:

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# = ‘001union 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’);

作者:yexx
來源:雲棲社群