MrE
MrE

Reputation: 1154

Retrieve username for 2 separate users on 2 separate things

I am trying a code my own forum system, and everything is going quite well, except for 1 thing.

When browsing a category, how would I be able to retrieve the username of both the creator of each thread, but also the username of the user who posted the last post in each thread?

This is what I have so far, but I still only retrieve 1 username (the OP's username).

SELECT 
    c_name, <-- category name
    t_title, <-- thread title
    t_by, <-- thread started by user id
    username, <-- username of the thread starter
    p_by, <-- post by user id
    p_date, <-- post posted date
    COUNT(p_id) as total_posts
FROM
    forum_categories
LEFT JOIN
    forum_threads
ON
    t_cat = c_id
LEFT JOIN
    forum_posts
ON
    p_thread = t_id
LEFT JOIN
    users
ON
    t_by = id
AND
    p_by = id
WHERE
    t_cat = 1

As you can see, I only retrieve the username of the thread starter. Is it even possible to do this with a single query?

Thanks

Upvotes: 0

Views: 35

Answers (1)

dani herrera
dani herrera

Reputation: 51665

You should left join for both users in your query:

SELECT 
    c_name,           <-- category name
    t_title,          <-- thread title
    t_by,             <-- thread started by user id
    ut_by.username,   <-- username of the thread starter
    p_by,             <-- post by user id
    up_by.username,   <-- username of the post
    p_date,           <-- post posted date
    COUNT(p_id) as total_posts
FROM
    forum_categories
       LEFT JOIN
    forum_threads
       ON t_cat = c_id
       LEFT JOIN
    forum_posts
       ON p_thread = t_id
       LEFT JOIN
    users ut_by
      ON t_by = ut_by.id 
      LEFT JOIN
    users up_by
      on p_by = up_by.id
WHERE
    t_cat = 1

This is an answer about get user details for both. Disclaimer about other mistakes that this query can contains.

Upvotes: 1

Related Questions