【MySQL】求每门科目成绩排名前二的学生信息
生活随笔
收集整理的這篇文章主要介紹了
【MySQL】求每门科目成绩排名前二的学生信息
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
建表語句如下:
學生表
成績表
CREATE TABLE score (sno VARCHAR(4) NOT NULL, kemu VARCHAR(5) NOT NULL, degree NUMERIC(10, 1) NOT NULL,foreign key(sno) references student(sno))ENGINE=INNODB DEFAULT CHARSET=utf8 ; -- 插入數(shù)據(jù) insert into student values(1001,'kb',18),(1002,'kd',19),(1003,'love',18),(1004,'wade',20),(1005,'jame',18),(1006,'bull',22),(1007,'nets',26),(1008,'suns',29)-- 插入數(shù)據(jù) insert into score values(1001,'語文',81),(1002,'語文',85),(1001,'數(shù)學',100),(1002,'英語',88),(1003,'py',99),(1004,'語文',70),(1001,'英語',98),(1002,'py',87),(1002,'數(shù)學',70),(1004,'py',85),(1004,'數(shù)學',56),(1001,'py',78)成績后的表如下所示:
如果要查找的字段在同一張表中
例如:查找每門科目成績排名前二的學生信息,顯示學號,科目,分數(shù)(單表查詢)
1、先取一個新表sc1,左連接至原表,對degree欄做比較,條件為sc1.kemu=sc2.kemu and sc1.degree<sc2.degree,其實就是列出同一門課內(nèi)所有分數(shù)比較的情況。出現(xiàn)兩次及以下,說明在這個科目中處于前2排名
select sc1.sno,sc1.kemu,sc1.degree from score sc1 where (select count(1) from score sc2 where sc1.kemu=sc2.kemu and sc1.degree<sc2.degree)<2 order by sc1.kemu,sc1.degree desc如果要查找的字段不在同一張表中
例如:取出符合每門科目成績排名前二的信息,顯示學號,姓名(在student表中),科目,分數(shù)(多表查詢)
1、先在score表中取出符合每門科目成績排名前二的信息,形成一個新表a;然后對表a與student表進行關(guān)聯(lián),輸出student和c表的需求列,得出結(jié)果。
select student.sno,student.sname,a.kemu,a.degree from student inner join (select sc1.sno,sc1.kemu,sc1.degree from score sc1 where (select count(1) from score sc2 where sc1.kemu=sc2.kemu and sc1.degree<sc2.degree)<2 order by sc1.kemu,sc1.degree desc) as a on student.sno=a.sno order by a.kemu,a.degree desc總結(jié)
以上是生活随笔為你收集整理的【MySQL】求每门科目成绩排名前二的学生信息的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL—事务隔离级别
- 下一篇: MySQL—视图(一)