0

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

我有以下架构:

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 ,我想显示用户名

4

1 回答 1

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

希望能帮助到你...

于 2012-03-13T09:34:15.547 回答