8

我有一张包含许多不同作者的博客文章的表格。我想做的是展示 10 位最新作者的最新帖子。

每个作者的帖子都按顺序简单地添加到表中,这意味着单个作者可以运行多个帖子。我有很多时间想出一个查询来做到这一点。

这给了我最后 10 个唯一的作者 ID;它可以用作子选择来抓取每个作者的最新帖子吗?

SELECT DISTINCT userid
FROM posts
ORDER BY postid DESC 
LIMIT 10
4

3 回答 3

3
select userid,postid, win from posts where postid in (
SELECT max(postid) as postid
FROM posts 
GROUP BY userid
) 
ORDER BY postid desc 
limit 10

http://sqlfiddle.com/#!2/09e25/1

于 2012-04-16T21:27:11.590 回答
1

您需要每个作者的最后一个 postid 的子查询,并按 postid DESC 排序。然后,将该结果连接到posts表中:

SELECT B.* FROM
(
    SELECT * FROM
    (
        SELECT userid,MAX(postid) postid
        FROM posts GROUP BY userid
    ) AA
    ORDER BY postid DESC
    LIMIT 10
) A INNER JOIN posts B
USING (user_id,post_id);

确保你有这个索引

ALTER TABLE posts ADD INDEX user_post_ndx (userid,postid);
于 2012-04-16T21:19:42.607 回答
1
SELECT userid
     , MAX(postid) AS lastpostid
FROM posts
GROUP BY userid
ORDER BY lastpostid DESC 
LIMIT 10
于 2012-04-16T22:02:20.687 回答