oracle查询从论坛中获取所有帖子

时间:2012-03-13 09:06:16

标签: sql oracle query-optimization query-builder

我正在构建一个使用Oracle作为我的rdbms的论坛,我遇到了1个查询的问题,该查询获取所有论坛帖子并显示一些数据。我遇到的问题是获得最后一次讨论海报。根据我的查询,我只设法得到最后一张海报的ID,但我想从用户表中获取他的用户名。这就是我所拥有的:

我有以下架构:

discussions
    id 
    course_id
    user_id
    title
    stub
    created_at

threads
    id
    discussion_id
    user_id
    created_at
    updated_at
    message

 discussion_views
     discussion_id
     user_id
     time

  users
     id
     username`

我提出这个问题:

select * from
(select discussions.created_at, 
        discussions.title, 
        users.username as discussion_created_by, 
        count(distinct threads.id) over (partition by discussions.created_at, 
                                                      discussions.title, 
                                                      users.username) AS replies, 
        count(distinct discussion_views.discussion_id) 
             over (partition by discussions.created_at, 
                                discussions.title, 
                                users.username) AS "views",
        threads.user_id AS latest_post_by,
        threads.updated_at AS latest_post_at,
        row_number() over (partition by discussions.created_at, 
                                        discussions.title, 
                                        users.username
                           order by threads.id desc) AS rn
 from discussions
 left join threads on discussions.id=threads.discussion_id
 left join discussion_views on discussions.id=discussion_views.discussion_id
 join users on users.id=discussions.user_id) sq
where rn=1
order by created_at desc

我将latest_post_by作为id,我想显示用户名

0 个答案:

没有答案