Search code examples
mysqlsqljoininner-join

How to use a select statement to show 2 different foreign keys that reference the same foreign key?


I have three tables that look like this,


User
id | FName | Lname | Email
---+-------+-------+----------------------
1  | Bob   | Jim   | [email protected]
2  | Smith | Jane  | [email protected]
3  | John  | Smith | [email protected]

post
id | description         | Title          | Postuser 
---+---------------------+----------------+----------
1  |   A large content   | A simple title | 2        
2  |   Small Content     |complex title   | 1        

Comments
id | Content             | Commentuser | CommentPost 
---+---------------------+-------------+-------------
1  |   A large content   | 2           |2
2  |   Small Content     | 1           |2

User ID is referenced by both Commentuser and Postuser. Post id is referenced by commentPost

For my select statement, I need to give the 2nd post's title, content, and the authors first name, the authors last name, and the authors email address for that post as well as any comments content made on the post with the comments authors first, last name, and email address, resulting in 2 rows

The user for the post is different than the user for the comment, so how would I select both to give both first and last names? The other chained joins I have seen on here do not cover this type of thing because there are 3 tables. I was given the skeleton code of

Select Post.Content, ... 
FROM User,...,User AS Author 
WHERE ... AND Author.id = ...; 

EDIT: expected result

|Content              | Title          | PostFName | PostLname | PostEmail     | Comment Content| Comment Firstname|comment Lastname|
-------------------------------------------------------------------------------------------------------------------------------------
|   Small Content     |complex title   | Bob       | Jim       | [email protected]| A large content| Smith           | Jane           |
|   Small Content     |complex title   | Bob       | Jim       | [email protected]| A small content| John            | Smith          |

Solution

  • You can join the user table multiple times; you just need to use aliases to avoid ambiguity:

    select p.description, p.title, 
        pu.fname postfname, pu.lname postlname, pu.email postemail,
        c.content commentcontent,
        cu.fname commentfname, cu.lname commentlname, cu.email commentemail
    from post p
    inner join user pu on pu.id = p.postuser
    inner join comments c on c.commentpost = p.id
    inner join user cu on cu.id = c.commentuser