在oracle的复杂查询中获取最后一个论坛海报

时间:2012-03-09 11:48:28

标签: sql oracle query-optimization

我正在为一个应用程序构建一个论坛,我很难尝试在讨论中获得最新的海报。我使用的数据库是Oracle。

我有以下表格:

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 discussions.created_at, 
       discussions.title, 
       users.username, 
       count(threads.id) AS "replies", 
       count(distinct discussion_views.discussion_id) AS "views" 
 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
 group by discussions.created_at, discussions.title, users.username
 order by discussions.created_at desc

我需要的是获取发布在帖子中的最后一位用户和日期。我应该制作内插件,连接件还是应该进行另一次插入。我还希望我的查询具有高效性,因为我的论坛需要处理大量流量。

1 个答案:

答案 0 :(得分:1)

尝试:

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.time) 
             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