从每个班级获得最佳学生限制3个结果

时间:2014-05-17 02:19:44

标签: mysql limit

我需要从每个班级得到2名最优秀的学生。试试这个

SELECT t1.nota,t2.sala,t3.serie
FROM aluno AS t1
LEFT JOIN sala AS t2 ON t1.sala = t2.id
LEFT JOIN serie AS t3 ON t1.serie = t3.id

ORDER BY t1.serie,t1.sala,t1.nota

LIMIT t1.nota 2 ??

实际查询结果:

 
nota    sala    serie
9       1-102   1 ano
8.9     1-102   1 ano
9.1     1-102   1 ano
8.2     1-201   2 ano
9       1-201   2 ano
7.8     1-201   2 ano
9       1-303   3 ano
10      1-303   3 ano
8.7     1-303   3 ano
10      1-102   1 ano

我需要

 
nota    sala    serie
10      1-102   1 ano
9.1     1-102   1 ano
8.2     1-201   2 ano
9       1-201   2 ano
9       1-303   3 ano
10      1-303   3 ano

------

CREATE TABLE IF NOT EXISTS `aluno` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `serie` int(11) NOT NULL,
  `sala` int(11) NOT NULL,
  `nota` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;



INSERT INTO `aluno` (`id`, `serie`, `sala`, `nota`) VALUES
(1, 1, 2, 9),
(2, 1, 2, 10),
(3, 2, 2, 8),
(4, 2, 2, 9),
(5, 1, 2, 10),
(6, 5, 2, 10),
(7, 3, 3, 8),
(8, 3, 3, 9),
(9, 3, 3, 10),
(10, 3, 3, 10);



CREATE TABLE IF NOT EXISTS `sala` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `serie` varchar(50) NOT NULL,
  `sala` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;



INSERT INTO `sala` (`id`, `serie`, `sala`) VALUES
(1, '1', '1-101'),
(2, '1', '1-102'),
(3, '1', '1-103'),
(4, '1', '1-104'),
(5, '2', '2-101'),
(6, '2', '2-102'),
(7, '2', '2-103'),
(8, '2', '2-104');



CREATE TABLE IF NOT EXISTS `serie` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `serie` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;



INSERT INTO `serie` (`id`, `serie`) VALUES
(1, '1 ano'),
(2, '2 ano');

1 个答案:

答案 0 :(得分:0)

@strawberry和@sgedds感谢您的尝试。我找到了

的解决方案
set @num := 0, @salas := '';
select t1.id, t3.serie,t2.sala, t1.nome,t1.nota,t1.sala,
  @num := if(@salas = t1.sala, @num + 1, 1) as row_number,
  @cols := t1.sala as dummy
from aluno AS t1
LEFT JOIN sala AS t2 on t1.sala = t2.id
LEFT JOIN serie AS t3 on t1.serie = t3.id
WHERE t2.id IN(10,11,12) AND t1.nota >='8'
having dummy <=11
ORDER BY t3.serie ASC,t2.sala ASC, t1.nota DESC,nome ASC