美文网首页
MySQL中MAX函数与Group By一起使用的注意事项

MySQL中MAX函数与Group By一起使用的注意事项

作者: Mracale | 来源:发表于2020-09-11 14:23 被阅读0次

测试目的:
对数据表中的数据进行分组求最大值,针对本测试,主要是求 每个班级中的年龄最大的学生

测试表student:

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
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 '年龄',
  `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);

表数据信息:

image.png

错误的写法

SELECT
    * 
FROM
    ( SELECT * FROM student order by age desc,class asc) AS b
GROUP BY
    `class`;

错误的结果:

image.png

正确的写法

SELECT
    * 
FROM
    ( SELECT * FROM student order by age desc,class asc limit 99999999) AS b
GROUP BY
    `class`;

正确的结果:

image.png

注意:
limit 99999999是必须要加的,如果不加的话,数据不会先进行排序,通过 explain 查看执行计划,可以看到没有 limit 的时候,少了一个 DERIVED(得到) 操作。

explain SELECT * FROM
( SELECT * FROM student order by age desc,class asc limit 99999999) AS b
GROUP BY class;

相关文章

网友评论

      本文标题:MySQL中MAX函数与Group By一起使用的注意事项

      本文链接:https://www.haomeiwen.com/subject/hfpvektx.html