2012-03-13 102 views
0

我正在建立一個使用Oracle作爲我的rdbms的論壇,而且我有一個查詢獲取所有論壇帖子並顯示一些數據的問題。我遇到的問題是獲得最後的討論海報。用我的查詢,我只設法得到最後一張海報的ID,但我想從用戶表中獲得他的用戶名。這是我有: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 * 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

你不能只替換'和'users.username threads.user_id AS latest_post_by' AS latest_post_by'? – Ollie 2012-03-13 09:12:47

+0

如果我替換它,users.username存儲在進行左連接時設置的討論帖子的值 – Mythriel 2012-03-13 09:29:25

回答

2

作爲對您評論的迴應,請在users表中添加另一個連接。

join users latest_poster ON (latest_poster.id=threads.user_id) 

然後更換:

threads.user_id AS latest_post_by 

有:

latest_poster.username AS latest_post_by 

這應該然後給你通過threads.user_id標識的用戶的用戶名。

希望它可以幫助...