Mysql按字段分组取最大值记录

    xiaoxiao2026-03-27  14

    要求:获得 按table1_id分组,并且age最大的记录信息,即2、3、5条 方法 一: select * from (select * from table2 order by age desc) as a group by a.table1_id 方法 二: select a.* from table2 as a where age = (select max(age) from table2 where a.table1_id=table1_id) 方法 三: select a.* from table2 as a where not exists (select * from table2 where table1_id=a.table1_id and age>a.age) 方法 四: select a.* from table2 as a where exists (select count(*) from table2 where table1_id=a.table1_id and age>a.age having count(*)=0)

    最近看了下评论都说第一个是错的,现在我把表结构和数据都发出来。注意:这里用的是mysql数据库

    CREATE TABLE `table2` ( `id` int(11) NOT NULL AUTO_INCREMENT, `table1_id` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, `aaa` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; INSERT INTO `table2` (`id`, `table1_id`, `age`, `aaa`) VALUES ('1', '1', '10', 'a1'); INSERT INTO `table2` (`id`, `table1_id`, `age`, `aaa`) VALUES ('2', '1', '20', 'a2'); INSERT INTO `table2` (`id`, `table1_id`, `age`, `aaa`) VALUES ('3', '2', '33', 'a3'); INSERT INTO `table2` (`id`, `table1_id`, `age`, `aaa`) VALUES ('4', '2', '11', 'a4'); INSERT INTO `table2` (`id`, `table1_id`, `age`, `aaa`) VALUES ('5', '3', '55', 'a5'); INSERT INTO `table2` (`id`, `table1_id`, `age`, `aaa`) VALUES ('6', '3', '44', 'a6');我不保证有啥特殊情况会产生啥其他问题,但就我上面的例子来说没看出什么毛病。

    参考资源: http://blog.sina.com.cn/s/blog_8155e74d0101g1pl.html
    转载请注明原文地址: https://ju.6miu.com/read-1308224.html
    最新回复(0)