聚合最后发布作者ID的SQL语句

时间:2013-02-02 01:40:00

标签: sql database

想象一下,我有一个包含以下关系模式的数据库:

forums(id, title)
forum_topics(id, forum_id, title, count_views, some_data)
forum_posts(id, topic_id, title, content, author_id, another_data)

并说我在forums_posts表中有两行数据:

(1, 1, 'some title', 'some content', 4, 'blahr')
(2, 1, 'another post title', 'my content', 5, 'nah')

现在,我想创建一个SQL语句,它将为我提供主题ID,该主题的帖子数以及该主题的最新贡献者的用户ID。获得前两个值显然不是问题,而后者非常棘手。这是我到目前为止所做的:

SELECT topic_id,
   COUNT(*) AS count_posts,
   forum_posts.author_id AS last_answer_by
FROM forum_posts
JOIN forum_topics ON forum_posts.topic_id = forum_topics.id
GROUP BY topic_id

上面给出的查询会给我,假设有一个id = 1的forum_topics条目:

topic_id = 1
count_posts = 2
last_answer_by = 4

虽然假设更高的帖子ID意味着它的编写时间晚于我想要的ID更低的帖子条目:

topic_id = 1
count_posts = 2
last_answer_by = 5

2 个答案:

答案 0 :(得分:2)

您只需要查询forum_posts表以获得所需的结果,但您需要在from子句中使用子查询首先获取forum_posts表中每个topic_id的帖子数量以及最大值该主题的帖子ID。然后,您将该子查询的结果加回到最大帖子ID上的原始forum_posts表:

SELECT postcounts.topic_id,
       count_posts,
       author_id as last_answer_by
FROM
  (SELECT topic_id,
          COUNT(*) AS count_posts,
          MAX(id) AS lastpost
   FROM forum_posts
   GROUP BY topic_id) postcounts
INNER JOIN forum_posts ON lastpost = forum_posts.id

答案 1 :(得分:0)

SELECT  a.topic_id,
        b.autor_ID as Last_Answer_By,
        d.TotalCount
FROM    forum_topics b
        INNER JOIN forum_posts a
            ON a.topic_id = b.id
        INNER JOIN
        (
            SELECT  topic_ID, MAX(ID) max_ID
            FROM    forum_posts
            GROUP   BY topic_ID
        ) c ON  b.topic_ID = c.topic_ID AND
                b.ID = c.max_ID
        INNER JOIN
        (
            SELECT  topic_ID, COUNT(*) TotalCount
            FROM    forum_posts
            GROUP   BY topic_ID
        ) d ON  a.topic_ID = d.topic_ID