sql 筛选每个ID的最新数据(根据创建时间排序 筛选最新的数据
需求:筛选出数据表中每个user_id的最新记录。
解决方法:根据分组获取 ID , max(时间) 函数获取最大的创建时间 ,根据时间和ID获取需要的对应记录 。
例如:
truncate table comment;
INSERT INTO `comment` (`id`, `user_id`, `content`, `addtime`, `lastmodify`) VALUES
(1, 1, '评论1', '2017-05-17 00:00:00', '2017-05-17 00:00:00'),
(2, 1, '评论2', '2017-05-17 00:10:01', '2017-05-17 00:10:01'),
(3, 2, '评论1', '2017-05-17 00:10:02', '2017-05-17 00:10:02'),
(4, 2, '评论2', '2017-05-17 00:00:03', '2017-05-17 00:00:03'),
(5, 3, '评论1', '2017-05-17 00:10:04', '2017-05-17 00:10:04'),
(6, 1, '评论3', '2017-05-17 00:00:05', '2017-05-17 00:00:05'),
(7, 4, '评论1', '2017-05-17 00:00:06', '2017-05-17 00:00:06'),
(8, 4, '评论2', '2017-05-17 00:10:07', '2017-05-17 00:10:07'),
(9, 4, '评论3', '2017-05-17 00:00:08', '2017-05-17 00:00:08'),
(10, 4, '评论4', '2017-05-17 00:00:09', '2017-05-17 00:00:09'),
(11, 3, '评论2', '2017-05-17 00:00:10', '2017-05-17 00:00:10');
select * from comment;
+----+---------+---------+---------------------+---------------------+
| id | user_id | content | addtime | lastmodify |
+----+---------+---------+---------------------+---------------------+
| 1 | 1 | 评论1 | 2017-05-17 00:00:00 | 2017-05-17 00:00:00 |
| 2 | 1 | 评论2 | 2017-05-17 00:10:01 | 2017-05-17 00:10:01 |
| 3 | 2 | 评论1 | 2017-05-17 00:10:02 | 2017-05-17 00:10:02 |
| 4 | 2 | 评论2 | 2017-05-17 00:00:03 | 2017-05-17 00:00:03 |
| 5 | 3 | 评论1 | 2017-05-17 00:10:04 | 2017-05-17 00:10:04 |
| 6 | 1 | 评论3 | 2017-05-17 00:00:05 | 2017-05-17 00:00:05 |
| 7 | 4 | 评论1 | 2017-05-17 00:00:06 | 2017-05-17 00:00:06 |
| 8 | 4 | 评论2 | 2017-05-17 00:10:07 | 2017-05-17 00:10:07 |
| 9 | 4 | 评论3 | 2017-05-17 00:00:08 | 2017-05-17 00:00:08 |
| 10 | 4 | 评论4 | 2017-05-17 00:00:09 | 2017-05-17 00:00:09 |
| 11 | 3 | 评论2 | 2017-05-17 00:00:10 | 2017-05-17 00:00:10 |
+----+---------+---------+---------------------+---------------------+
根据上面的表格字段进行sql语句的查询。
select a.* from comment as a right join
(select user_id, max(addtime) as maxtime from comment where user_id is not null group by user_id) as b
on a.user_id=b.user_id and a.addtime=b.maxtime order by a.user_id asc;
+------+---------+---------+---------------------+---------------------+
| id | user_id | content | addtime | lastmodify |
+------+---------+---------+---------------------+---------------------+
| 2 | 1 | 评论2 | 2017-05-17 00:10:01 | 2017-05-17 00:10:01 |
| 3 | 2 | 评论1 | 2017-05-17 00:10:02 | 2017-05-17 00:10:02 |
| 5 | 3 | 评论1 | 2017-05-17 00:10:04 | 2017-05-17 00:10:04 |
| 8 | 4 | 评论2 | 2017-05-17 00:10:07 | 2017-05-17 00:10:07 |
+------+---------+---------+---------------------+---------------------+
上面则会出呈现出每个人的最新记录。