0

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

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
4

2 回答 2

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
于 2013-02-02T02:11:59.747 回答
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
于 2013-02-02T01:56:36.993 回答