MySQL uses gourp by to get the maximum value and latest data of a field after grouping
1. Business description
In daily development, everyone inevitably encounters business requirements such as grouping a table and taking the maximum value and the latest value, which involves the group by and max functions. for example:
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');
Here is a business: take out everyone's best score in a single subject.
Second, the problem reappears
My first thought of SQL is:
select name,subject,max(score) from score group by name
The result of the operation is:
you can see that the name and score are correct, but the subjects are all Chinese. Obviously inconsistent with reality! (Group by takes the first data by default)
Note:
I tried again here to sort first, then group values, but the result is still the same as above
select
temp.name,temp.subject,max(temp.score)
from
(select * from score order by score desc) temp
group by temp.name
Three, the solution
1. First take out the name and maximum score
select name,max(score) from score group by name
2. Use the data queried above as a temporary table to query the original table
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
The final result is: the
problem is solved, I hope it can help everyone. If you have a better solution, please leave a message in the comment area.