MySQL group by 后取最大(小)值记录

位置:首页>文章>详情   分类:教程分享   阅读(85)   2023-09-04 17:42:51

测试数据

测试数据

测试数据SQL:

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT '' COMMENT '姓名',
`age` int(3) NULL DEFAULT 0 COMMENT '年龄',
`c_class` int(4) NULL DEFAULT 0 COMMENT '班级',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 7 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
 
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1, '张三', 22, 1);
INSERT INTO `student` VALUES (2, '李四', 26, 1);
INSERT INTO `student` VALUES (3, '王五', 20, 2);
INSERT INTO `student` VALUES (4, '赵六', 20, 2);
INSERT INTO `student` VALUES (5, '孙七', 22, 3);
INSERT INTO `student` VALUES (6, '李八', 28, 3);
INSERT INTO `student` VALUES (7, '阿九', 28, 3);

 

需求:查询每个班级年龄最大的学生

 

方法一:排序+limit实现

-- 方法一:通过排序+limit (注意limit必须加否则不会排序)
SELECT * from (
SELECT * from student a order by a.age desc,a.c_class asc LIMIT 99999999
)tmp GROUP BY tmp.c_class;

查询结果:

查询结果

 

方法二:排序+having函数实现

-- 方法二:使用having函数
SELECT * from (
SELECT * from student a WHERE age >1  HAVING 1 order by a.age desc,c_class asc
)tmp GROUP BY tmp.c_class;

提示:这里的where age>1 是标注条件写的地方,实际可有可无根据需求来。

查询结果:

结果2

 

两种方式都能查询出来。

 

注意:不要使用max() 或者min()函数,查出来数据不对。

 

 

 

地址:https://www.leftso.com/article/1698631337939832833.html