mysql实现求每门课程的前3名

最近因为工作需要遇到此类问题,现简化思路,写一个简单的SQL实例。

mysql中没有row number() over() 函数,对与求每科的前3名这类问题稍微复杂。

希望对您能有所帮助。

建表:

DROP TABLE IF EXISTS score;
CREATE TABLE score ( 
id int(10) NOT NULL AUTO_INCREMENT, 
subject_id int(10) UNSIGNED DEFAULT NULL DEFAULT 0, 
student_id int(10) UNSIGNED DEFAULT NULL DEFAULT 0, 
score float DEFAULT NULL DEFAULT -1, 
PRIMARY KEY (id) 
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 

DROP TABLE IF EXISTS student;
CREATE TABLE student ( 
id int(10) NOT NULL AUTO_INCREMENT, 
name varchar(10) DEFAULT NULL DEFAULT 0, 
PRIMARY KEY (id) 
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 

DROP TABLE IF EXISTS subject;
CREATE TABLE subject ( 
id int(10) NOT NULL AUTO_INCREMENT, 
name varchar(10) DEFAULT NULL DEFAULT 0,
PRIMARY KEY (id) 
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 

数据准备:

insert into student(name) values('黄香蕉'),('小飞飞'),('小灰灰'),('小公主'),('大灰狼'),('青苹果');

insert into subject(name) values('java'),('php'),('oracle'),('mysql'),('计算机'),('数学');

insert into score(subject_id,student_id,score) values
(1,1,55),
(1,3,67),
(2,3,70),
(1,4,42),
(1,5,65),
(2,1,95),
(2,2,66),
(2,4,32),
(4,4,82),
(2,5,95),
(3,5,55),
(2,6,25),
(3,1,95),
(3,2,80),
(3,3,47),
(5,4,92),
(3,6,25),
(4,1,95),
(4,2,76),
(6,5,65),
(4,3,97),
(4,5,65),
(4,6,25),
(5,1,95),
(5,2,56),
(5,3,87),
(5,5,75),
(5,6,25),
(6,1,35),
(6,2,76),
(1,6,25),
(6,3,57),
(6,4,72),
(6,6,85);

答案:
---------------------------------------------------------------------------------

select  subject_id,student_id,score

from score sc1    

where  (select count(1) from score sc2 where sc2.subject_id=sc1.subject_id and sc2.score >= sc1.score) <=3

order by subject_id ,score desc;

--------------------------------------------------------------------------

猜你喜欢

转载自blog.csdn.net/adayan_2015/article/details/81080586