1

I have a database called "forum" with the tables:

  • "users", containing: user_id, username, password
  • "posts", containing: post_id, user_id (FK from "users"), type, title, content
  • "comments", containing: comment_id, user_id (FK from "users"), post_id (FK from posts"), content

At the moment, i'm using the query:

SELECT *
FROM forum.comments 
JOIN forum.posts ON (comments.post_id = posts.post_id) 
JOIN forum.users ON (posts.user_id= users.user_id)

With this query i can only display the username of the person who made the post, not the comment. How can i change this to show who made the comment, AND who made the post in the same query?

(If someething in the query is written wrong, it's just cause i had to translate it from another language, the query does return results).

1
  • was not aware of that option, thanks Gordon Linoff Commented Apr 13, 2016 at 14:47

1 Answer 1

4

You can join the table more than once if you alias the tables:

SELECT * FROM forum.comments AS c
JOIN forum.posts AS p ON (comments.post_id = posts.post_id)
JOIN forum.users AS u1 ON (posts.user_id = users.user_id)
JOIN forum.users AS u2 ON (comments.user_id = users.user_id)

When you do that, you can reference columns from the table by doing something like SELECT u1.username, u2.username ....

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the quick reply! :)
To increase readability i would use the aliases up (user of post) instead of u1 and uc (user of comment) instead of u2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.