【问题标题】:MySQL - Selecting the most recent post by each of the 10 most recent authorsMySQL - 选择最近 10 位作者的最新帖子
【发布时间】:2012-04-16 21:07:12
【问题描述】:

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

每个作者的帖子都只是按顺序添加到表格中,这意味着单个作者可能会发布一系列帖子。我有很多时间想出一个查询来做到这一点。

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

SELECT DISTINCT userid
FROM posts
ORDER BY postid DESC 
LIMIT 10

【问题讨论】:

    标签: mysql


    【解决方案1】:
    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

    【讨论】:

    • 这很接近 - 它返回每个用户 ID 的最新 postid,但行中的其余数据不匹配。例如,这不起作用: SELECT userid, title, bodytext, MAX(id) id FROM posts GROUP BY userid ORDER BY id DESC LIMIT 10
    • right 如果你想要所有字段,不幸的是你需要一个子查询。我编辑了我的答案。
    • 太好了,很高兴我能帮上忙。接受正确答案会更好:)
    【解决方案2】:

    您需要对每个作者的最后一个 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);
    

    【讨论】:

    • 你不应该需要用户 ID 和 postID 上的复合索引,因为 postID 无论如何都是唯一标识符,并且只存在于发帖的一位作者。
    • @DRapp 需要复合索引来加速子查询 AA(全索引扫描 vs 全表扫描)
    【解决方案3】:
    SELECT userid
         , MAX(postid) AS lastpostid
    FROM posts
    GROUP BY userid
    ORDER BY lastpostid DESC 
    LIMIT 10
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 2010-11-24
      • 2014-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多