select查詢語句,作為測試人員,使用此語句是家常便飯,是必須掌握的部分,由開始學習mysql到網上搜尋試題做,開始做題一塌糊塗,拿到題目就暈,無從下手,現在慢慢總結了一套自己做題的方式,很開森,嘿嘿!由簡單試題到較難試題的解答,思路其實都是一樣的,今天将做題思路進行總結,(說明:用到的關鍵字等自行學習,隻講解題思路)詳見如下:
我們在查詢時會用到的表,有4張表格如下:
1、查詢出‘計算機系’教師所教課程的成績表
解題思路:
1.1)首先根據題目要求,找到相關聯表,此處涉及到的表為:教師表、課程表、成績表
1.2)找到三張表之間的關聯點,如:teacher表與course表,相關聯點:tno。course表與score表,相關聯點:sno
首先已将題目進行拆解,拆解之後一步一步進行查詢,直到查詢到題目要求的結果,根據題目解題步驟分為3步,同時每步帶了具體的查詢語句:
第1步:查找‘計算機系’在哪個表中,根據圖可看出‘計算機系’在teacher表中。并且列名顯示為depart,根據此些資訊查找代表‘計算機系’的教師編号:
select tno from teacher where depart = '計算機系'; #1、結果:tno為:804、825
第2步:根據第1步的查找的tno結果在相關聯的course課程表中查找tno對應的sno資料,是以需将“第1步”作為條件
select cno from course where tno in (select tno from teacher where depart = '計算機系') #2、結果:3-105、3-245
第3步:前2步已經将‘計算機系’的老師與所教課程查找完成,最後剩下查找成績,是以将‘第2步’查找的cno結果作為條件,在成績表中查找sno值對應的成績即可select cno,degree from score where cno in(select cno from course where tno in (select tno from teacher where depart = '計算機系')) #3、結果:cno為3-105、3-245對應的degree将全部顯示出來
#運作第3步,顯示的就是題目要求的結果
2、查詢出‘李誠’老師教的學生的最高成績,結果顯示:最高成績的學生基本資訊以及成績
解題思路:
第1步:查詢‘李誠’老師的tno
select tno from teacher where tname='李誠' #結果顯示:804
第2步:已第1步的查詢結果為條件,在course課程表中查找tno對應的cno課程編号
select cno from course where tno in(select tno from teacher where tname='李誠') #結果顯示:3-245
第3步:已第2步的cno結果為第三步的條件,查找出cno課程編号在score成績表中對應的成績.此處為檢視結果的正确性,在結果顯示時添加了cno
select cno,degree from score where cno in (select cno from course where tno in(select tno from teacher where tname='李誠')) #查詢結果:3-245對應的成績有:86,75,68
第4步:第3步完成後,已經将‘李誠’老師教的學生成績全部查出來了,根據題目要求,需要查找最高成績,是以将第3步進行修改,需要用到max(查找最大)
select cno,max(degree) from score where cno in (select cno from course where tno in(select tno from teacher where tname='李誠'))
第5步:以上4步已經将老師對應的學生最高成績查詢出來,剩一步為顯示學生基本資訊,需要用到student表,是以需要将score與student兩個表關聯起來,使用sno
select s.*,cno,max(degree) from score sc,student s where cno in (select cno from course where tno in(select tno from teacher where tname='李誠')) and s.sno = sc.sno;
#運作第5步顯示的就是題目要求的結果
3、查詢出4位老師,每個老師教的成績最高的學生,結果顯示:學生基本資訊、老師基本資訊、課程名稱、成績,并按成績由高到低展示
#試題的解答案本寶寶已經列在下方,根據上面寫的解題思路,将此答案進行了解就可以啦
select s.*,t.*,sc.cno,sc.degree
from teacher t,course c,score sc , student s
where sc.cno in(select cno from course where tno in(select tno fromand= c.tno and c.cno = sc.cno and s.sno = sc.sno group by sc.cno order by degree desc;
解題思路總結:
1、分解試題
2、查找分解試題之後所要對應的表
3、查找對應表之間的關聯點
4、一步一步按照分解步驟實作,最後結果就出來啦
完事,本寶寶将mysql查詢的解題思路寫完了,解題思路梳理清楚,在難的查詢題也不怕,公司目前就剩我一個人啦,趕緊跑回家~~端午節走起!
1.作者:Syw