我正在尝试编写一个查询来选择我的所有论坛并获得相应的最新帖子(包括作者)......但我失败了。
这是我的结构:
forums forum_threads forum_posts
---------- ------------- -----------
id id id
parent_forum (NULLABLE) forum_id content
name user_id thread_id
description title user_id
icon views updated_at
created_at created_at
updated_at
last_post_id (NULLABLE)
这是我目前的查询:
SELECT forum.id, forum.name, forum.description, forum.icon, post_user.username
FROM forums AS "forum"
LEFT JOIN forum_posts AS "post" ON post.thread_id = (
SELECT id
FROM forum_threads
WHERE forum_id = forum.id
ORDER BY updated_at DESC LIMIT 1)
LEFT JOIN users AS "post_user" ON post_user.id = post.user_id
WHERE forum.parent_forum = 1
GROUP BY forum.id
当然这个查询不正确,因为一个帖子中有很多帖子......
有人可以帮忙吗?我正在使用PostgreSQL btw。
哦:我忘记了: 目前,我遍历所有“类别”(拥有parent_forum = NULL的论坛),然后为每个论坛运行一个额外的查询(这就是我在查询中看到parent_forum = 1的原因)。有没有更好的方法呢?
编辑: 我的上一篇文章是 forum_posts
中updated_at上最新日期的帖子答案 0 :(得分:2)
DISTINCT ON
应该让这更容易:
SELECT DISTINCT ON (f.id)
f.id, f.name, f.description, f.icon, u.username
FROM forums f
LEFT JOIN forum_threads t ON t.forum_id = f.id
LEFT JOIN forum_posts p ON p.thread_id = t.id
LEFT JOIN users u ON u.id = p.user_id
WHERE f.parent_forum = 1
ORDER BY f_id, p.updated_at DESC;
根据您的Q更新,最新帖子是最新的帖子forum_posts.updated_at
假设列定义为NOT NULL
。
答案 1 :(得分:1)
这是你的想法吗?您可以使用子查询获取给定论坛的最新帖子。
SELECT forums.id, forums.name, forums.description, forums.icon,
(SELECT username FROM forum_threads AS ft
JOIN forum_posts AS fp ON ft.id = fp.thread_id
JOIN users AS u ON fp.user_id = u.user_id
WHERE ft.forum_id = forums.id
ORDER BY updated_at DESC LIMIT 1) AS username_of_latest_post
FROM forums