在一次面試中被問到手寫出一條mysql查詢各科成績的前三名,
首先創建表:
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) DEFAULT NULL,
`subject_id` bigint(20) DEFAULT NULL,
`score` double(5,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4;
/*Data for the table `test` */
insert into `test`(`id`,`user_id`,`subject_id`,`score`) values
(1,1,1,1.00),
(2,1,1,2.00),
(3,2,1,3.00),
(4,3,1,6.00),
(5,1,2,3.00),
(6,2,2,3.00),
(7,3,2,8.00),
(8,4,2,10.00);
sql如下:
SELECT a.* FROM test a
LEFT JOIN test b ON a.subject_id=b.subject_id AND a.score<b.score
GROUP BY a.user_id,a.subject_id,a.score HAVING COUNT(b.id)<3
ORDER BY a.subject_id,a.score DESC
感謝大神同事磊哥的提醒幫助;