一、业务说明
大家在日常开发中不可避免遇到对某个表分组后取最大值、最新值等业务需求,这就涉及到group by、max函数。 举个例子:
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for score -- ---------------------------- DROP TABLE IF EXISTS `score`; CREATE TABLE `score` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(36) DEFAULT NULL, `subject` varchar(36) DEFAULT NULL, `score` int(10) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of score -- ---------------------------- INSERT INTO `score` VALUES ('1', '张三', '语文', '92'); INSERT INTO `score` VALUES ('2', '张三', '数学', '100'); INSERT INTO `score` VALUES ('3', '李四', '语文', '95'); INSERT INTO `score` VALUES ('4', '李四', '数学', '75'); INSERT INTO `score` VALUES ('5', '王五', '语文', '85'); INSERT INTO `score` VALUES ('6', '王五', '数学', '96'); INSERT INTO `score` VALUES ('7', '张三', '英语', '99'); INSERT INTO `score` VALUES ('8', '李四', '英语', '76'); INSERT INTO `score` VALUES ('9', '王五', '英语', '99');
这里有个业务:取出每个人的单科最好成绩。
二、问题复现
我个人首先想到的sql是:
select name,subject,max(score) from score group by name
运行结果却是:
大家可以看到,名字和分数没错,但科目却都是语文。显然与实际不符!(group by 默认取第一条数据)
注:
我这里又试了一下先进行排序,再分组取值,但结果还是和上面一样
select temp.name,temp.subject,max(temp.score) from (select * from score order by score desc) temp group by temp.name
三、解决办法
1.先取出姓名、最大分数
select name,max(score) from score group by name
2.把上面查询的数据作为临时表与原表关联查询
select temp_b.name,temp_b.subject,temp_b.score from (select name,max(score) score from score group by name) temp_a inner join score temp_b on temp_a.name = temp_b.name and temp_a.score = temp_b.score
最后的结果为:
问题解决,希望可以帮助到大家。如果大家有更好的解决方案,欢迎评论区留言。