【发布时间】:2016-08-03 08:48:15
【问题描述】:
我有一个普通的 cmets 表:
| id | comment | date | user | post | status |
我想获取我最后的 10 个 cmets,每个用户只有 1 条评论,我的意思是这样的:
我有这些数据:
| id | comment | date | user | post |
| 1 | text1 | 2016-04-01| 1 | 1 |
| 2 | text2 | 2016-04-02| 2 | 1 |
| 3 | text3 | 2016-04-03| 1 | 2 |
| 4 | text4 | 2016-04-04| 4 | 3 |
| 5 | text5 | 2016-04-04| 3 | 5 |
| 6 | text6 | 2016-04-05| 2 | 4 |
| 7 | text7 | 2016-04-07| 5 | 3 |
| 8 | text8 | 2016-04-10| 4 | 9 |
| 9 | text9 | 2016-04-11| 3 | 7 |
| 10 | text10 | 2016-04-12| 5 | 8 |
我想得到这个:
| 10 | text10 | 2016-04-12| 5 | 8 |
| 9 | text9 | 2016-04-11| 3 | 7 |
| 8 | text8 | 2016-04-10| 4 | 9 |
| 6 | text6 | 2016-04-05| 2 | 4 |
| 3 | text3 | 2016-04-03| 1 | 2 |
我使用这个sql语句:
SELECT *
FROM `comments`
GROUP BY `user`
ORDER BY MAX(`id`) DESC
这会获取用户的正确顺序但评论日期顺序错误的 cmets:
| 7 | text7 | 2016-04-07| 5 | 3 |
| 9 | text9 | 2016-04-11| 3 | 7 |
| 4 | text4 | 2016-04-04| 4 | 3 |
| 6 | text6 | 2016-04-05| 2 | 4 |
| 1 | text1 | 2016-04-01| 1 | 1 |
【问题讨论】:
标签: mysql greatest-n-per-group