I am building a forum using Oracle as my rdbms and I am having problems with 1 query that fetches all the forum posts and displays some data. The issue I am having is getting the last discussion poster. With my query I only managed to get the last poster’s id , but I want to get his username from the users table. This is what I have:
I have the following schema:
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`
And I make this query:
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
I am getting latest_post_by as id , I want to display the username
In response to your comment, add another join to the
userstable.Then replace:
with:
This should then give you the username of the user identified by
threads.user_id.Hope it helps…