mysql實(shí)戰(zhàn)--子查詢(xún),聚合,分組,左連接

表結(jié)構(gòu)如下:

  • 學(xué)生資料表
Paste_Image.png
  • 學(xué)生的成績(jī)表,sid就是學(xué)生資料表的外鍵
Paste_Image.png

分?jǐn)?shù)最高的學(xué)生信息,科目

方法一:左連接
select s.course as 科目,max(s.score1) as 最高分,c.name as 姓名 from score s left join student c on c.id = s.sid group by s.course;

方法二:子查詢(xún)
select course as 科目,max(score1) as 最高分,(select name from student c where c.id=s.sid) as 姓名 from score s group by course;

Paste_Image.png

科目評(píng)價(jià)為良好,性別為女的學(xué)生信息,科目

select s.score1,s.course,c.name,c.sex  from score s join student c on  s.sid=c.id where s.comment='良好' and c.sex='女';

Paste_Image.png

最低分?jǐn)?shù)性別為男和女的信息

select course,min(score1) as 最低分,c.sex,c.name from score s join student c on s.id=c.id and c.sex='男' or sex='女' group by course; 

Paste_Image.png

每科的前兩名學(xué)生信息

select course,score1, c.name from score s1 left join student c on c.id=s1.sid where 2>(select count(*) from score s where s.course = s1.course and s.score1>s1.score1)  order by s1.course,s1.score1  

Paste_Image.png

還有其他的兩種方法可以取前兩名學(xué)生數(shù)據(jù):

方法二:select a.id,a.SName,a.ClsNo,a.Scorefrom Table1 a left join Table1 b on a.ClsNo=b.ClsNo and a.Score<b.Scoregroup by a.id,a.SName,a.ClsNo,a.Scorehaving count(b.id)<2order by a.ClsNo,a.Score desc

方法三:select *from Table1 awhere id in (select id from Table1 where ClsNo=a.ClsNo order by Score desc limit 2)order by a.ClsNo,a.Score desc
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容