I am trying to join 3 mysql tables; friends, users, and comments.
users:
id | firstName | lastName
--------------------------
12 | edwin | leon
9 | oscar | smith
1 | kasandra | rios
friends:
userId | friendID
----------------------
12 | 9
9 | 12
12 | 1
1 | 12
comments:
commenter | comment | commentDate
----------------------------
12 | hey | Oct-2
1 | Hmmmmmm | Nov-1
9 | ok | Nov-2
9 | testing | Nov-2
1 | hello | Dec-20
1 | help | Dec-20
So what Im trying to do is select all of the user’s friend’s comments. So What I want to output is the comments that your friend made:
ex:
for edwin leon (id 12) it would output this
friendID | comment | commentDate | firstName | lastName
-----------------------------------------------------------
1 | Help | Dec-20 | kasandra | rios
1 | Hello | Dec-20 | kasandra | rios
9 | testing | Nov-2 | oscar | smith
9 | ok | Nov-2 | oscar | smith
1 | Hmmmm | Nov-1 | kasandra | rios
it would get all the friends comments but not his. Here is my code:
SELECT friends.friendID, users.firstName, users.lastName, comments.comment, comments.commentDate
FROM users
JOIN friends ON friends.userID = users.id
JOIN comments ON comments.commenter = friends.friendID
WHERE users.id = '12' AND comments.commenter != '12'
It does work but instead of getting the commenter’s name, I get edwin leon for all of them
You want to join the user table to the friendId rather than the userid:
See it working online: sqlfiddle