postgresql 查询一个表的数据沿着另一个表的最新记录

k4ymrczo  于 2023-03-01  发布在  PostgreSQL
关注(0)|答案(1)|浏览(164)

我在一个论坛一样的网站上工作,我必须在给定的类别中查询其最新的职位类别列表。
这些是表模式

create table forum_posts (
    forum_post_id text not null unique,
    forum_post_name text not null,
    user_id text not null references users(user_id),
    forum_category_id text not null references forum_categories(forum_category_id),
    forum_post_content text not null,
    forum_post_is_active boolean not null default true,
    forum_post_created_timestamp timestamptz not null default now(),
    -- gets updated when user
    --
    -- have edited the post
    -- new reply
    -- user have un-deactivate (goes from deactivated to activated) the post.
    forum_post_last_active_timestamp timestamptz not null default now(),
    -- when forum_post_is_active gets switch to false, deactivated timestamp gets updated
    forum_post_deactivated_timestamp timestamptz,
    forum_post_is_category_based_announcement boolean not null default false,
    forum_post_is_global_announcement boolean not null default false,
    primary key (forum_post_id)
);

create table forum_categories (
    forum_category_id text not null unique,
    forum_category_name text not null unique,
    forum_category_representative_id text not null unique,
    user_id text not null,
    forum_category_color_theme text not null default '#000000',
    forum_category_created_timestamp timestamptz not null default now(),
    primary key (forum_category_id),
    foreign key (user_id) references users(user_id)
);

我想要查询的是forum_posts表中包含最新帖子的类别列表。我尝试创建下面的查询,但不确定如何编写where子句

select
    forum_categories.forum_category_id,
    count(forum_posts.forum_post_id) as post_count,
    forum_posts.forum_post_id as latest_post_id,
    forum_posts.forum_post_created_timestamp as latest_post_timestamp
from forum_categories
inner join forum_posts on forum_categories.forum_category_id = forum_posts.forum_category_id
where -- how do I write the where clause here.

谢谢你的帮助。

clj7thdc

clj7thdc1#

我已经用with语句解决了部分问题

WITH first_row AS (
SELECT RANK() OVER (PARTITION BY forum_posts.forum_category_id ORDER BY forum_posts.forum_post_created_timestamp DESC) AS created_rank,
         forum_posts.forum_category_id,
         forum_posts.forum_post_id,
         forum_posts.forum_post_created_timestamp
    FROM forum_posts
)
SELECT  created_rank,
      forum_category_id,
      forum_post_id,
      forum_post_created_timestamp
FROM first_row
WHERE created_rank= 1

感谢Reddit上一个人

相关问题