You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
baseService/Doc/Mysql获取Group By的最新一条数据.txt

32 lines
992 B

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

MySQL用GROUP BY分组取最新一条数据
因为group by后取的一条数据默认是按主键id排序后的第一条
而且mysql查询语句是先执行group by再执行order by的。
所以无法直接取 group by 后 创建时间最新的数据。
通过max()取最大id。
操作测试:
1、数据准备
CREATE TABLE `stu2` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` char(16) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of stu2
-- ----------------------------
INSERT INTO `stu2` VALUES ('1', '李四');
INSERT INTO `stu2` VALUES ('2', '王五23');
INSERT INTO `stu2` VALUES ('3', '王五23');
INSERT INTO `stu2` VALUES ('4', '王五23');
INSERT INTO `stu2` VALUES ('5', '李四');
select max(id),name from stu2 group by name;
select max(id) id,name from stu2 group by name order by id;
INSERT INTO `stu2` VALUES ('6', '李四');