mysql使用distinct(关键) order by group 查询成绩表中每个学生时间最近的成绩数据
sql初始化
-- -------------------------------------------------------- -- 主机: 127.0.0.1 -- 服务器版本: 8.0.15 - MySQL Community Server - GPL -- 服务器操作系统: Win64 -- HeidiSQL 版本: 9.5.0.5196 -- -------------------------------------------------------- /*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @[email protected]@SQL_MODE, SQL_MODE=‘NO_AUTO_VALUE_ON_ZERO‘ */; -- 导出 表 test.score 结构 CREATE TABLE IF NOT EXISTS `score` ( `score_id` bigint(20) NOT NULL AUTO_INCREMENT, `student_name` varchar(32) DEFAULT NULL, `course` varchar(30) DEFAULT NULL, `score` int(11) DEFAULT NULL, `create_time` datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`score_id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- 正在导出表 test.score 的数据:~8 rows (大约) /*!40000 ALTER TABLE `score` DISABLE KEYS */; INSERT INTO `score` (`score_id`, `student_name`, `course`, `score`, `create_time`) VALUES (1, ‘张三‘, ‘语文‘, 66, ‘2019-07-24 10:35:05‘), (2, ‘张三‘, ‘数学‘, 88, ‘2019-12-24 10:35:05‘), (3, ‘张三‘, ‘英语‘, 92, ‘2019-02-24 10:35:05‘), (4, ‘李四‘, ‘语文‘, 95, ‘2019-06-24 10:35:05‘), (5, ‘李四‘, ‘数学‘, 55, ‘2019-08-24 10:35:05‘), (6, ‘李四‘, ‘英语‘, 22, ‘2019-03-24 10:35:05‘), (7, ‘王五‘, ‘语文‘, 99, ‘2019-06-23 10:35:05‘), (8, ‘王五‘, ‘数学‘, 88, ‘2019-08-24 10:35:05‘), (9, ‘王五‘, ‘英语‘, 77, ‘2019-05-24 10:35:05‘); /*!40000 ALTER TABLE `score` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, ‘‘) */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET [email protected]_CHARACTER_SET_CLIENT */;
执行sql
SELECT * FROM ( SELECT DISTINCT * FROM score ORDER BY create_time DESC ) s GROUP BY s.student_name;
结果展示
2 张三 数学 88 2019-12-24 10:35:05
5 李四 数学 55 2019-08-24 10:35:05
8 王五 数学 88 2019-08-24 10:35:05