lomas09
lomas09

Reputation: 1104

Mysql Join more that 2 tables

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

Upvotes: 3

Views: 335

Answers (3)

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

Try this (I haven't tested it)

SELECT friends.friendID, u2.firstName, u2.lastName, comments.comment, comments.commentDate  
FROM users AS u
  JOIN friends ON friends.userID = u.id
  JOIN comments ON comments.commenter = friends.friendID 
  JOIN users AS u2 ON u2.id = friends.friendID
 WHERE u.id = '12' AND comments.commenter != '12'

Upvotes: 0

Sashi Kant
Sashi Kant

Reputation: 13465

Try this::

Select friendId, comment, commentdate, firstname, lastname
from
friends inner join comments on (friends.friendId=comenter)
inner join users on (users.id=friends.friendId)
where friends.userid=?

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 839194

You want to join the user table to the friendId rather than the userid:

SELECT friends.friendID, users.firstName, users.lastName, comments.comment, comments.commentDate  
FROM users
  JOIN friends ON friends.friendID = users.id
  JOIN comments ON comments.commenter = friends.friendID 
 WHERE friends.userID = '12' AND comments.commenter != '12'

See it working online: sqlfiddle

Upvotes: 3

Related Questions