mysql查询各科成绩的前三名

在一次面试中被问到手写出一条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

感谢大神同事磊哥的提醒帮助;

你可能感兴趣的:(MySQL)