在查询时出现了 根据ID 分组自动获取到最早的一条记录 >>>>这里我要获取的是最新的记录 所以是有问题
解决方法根据分组获取 ID ,yong 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 |
+----+---------+---------+---------------------+---------------------+
这里就是处理的DOME
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 |
+------+---------+---------+---------------------+---------------------+
转至 :https://blog.csdn.net/fdipzone/article/details/72453553