选择唯一的限制

时间:2015-12-18 12:41:42

标签: mysql greatest-n-per-group

以下是一个例子:

sql and result

如您所见,前4个记录具有相同的topic_id编号。如何使用唯一的topic_id获取最后10条记录?

感谢。

PS正确的结果示例:

id        user_id    topic_id   ...
306114    14331      26164      ...
306110    14331      27001      ...
306109    14331      26660      ...
...       ...        ...        ...

1 个答案:

答案 0 :(得分:0)

SELECT posts.id, posts.user_id, posts.text, posts.topic_id, posts.updated_at, topics.name as topic_name, topics.forum_id FROM my_forum_posts AS posts
                      ...
                      WHERE posts.id IN (SELECT MAX(id) FROM my_forum_posts GROUP BY topic_id)
                      ORDER BY posts.id DESC LIMIT 10