2012-03-13 11 views
0

私はOracleをrdbmsとして使用してフォーラムを構築しています。フォーラムのすべてのポストを取得してデータを表示する1つのクエリに問題があります。私が持っている問題は最後のディスカッションポスターを得ることです。私のクエリでは、最後の投稿者の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 

私はIDとしてlatest_post_by取得しています、私は、ユーザー名を表示したい

+0

は、あなただけの 'AS latest_post_by' users.username'とAS latest_post_by' threads.user_id置き換えることができませんでした...それがお役に立てば幸いですか! – Ollie

+0

私がそれを置き換えると、users.usernameは、左の結合を行うときに設定されたディスカッションポスターの値を格納します – Mythriel

答えて

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で識別されるユーザのユーザ名を与える必要があります。

関連する問題