想象一下,我有一个具有以下关系模式的数据库:
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