Not sure if my title explains it very well so here’s an example. I have two MYSQL tables, comments and votes_comments which are matched based on a field comment_id. For sample data comments has two rows and votes_comments has one row which matches one of the comments row. AKA Two comments were written and a single person voted on one of them Given that, the following query returns 2 rows:
SELECT comments.*, users.username FROM comments
JOIN users ON users.user_id = comments.user_id
WHERE comments.track_id=6 AND comments.parent_id=-1
GROUP BY comments.comment_id
Now what I want to do is join on votes_comments which may or may not have a matching row. What I want to do is grab the matching value if it exists or return null in the column if there is no matching result. AKA: Did the user vote it up, down or not at all (null). Here is my modified query:
SELECT comments.*, users.username, votes_comments.vote FROM comments
JOIN users ON users.user_id = comments.user_id
LEFT JOIN votes_comments ON votes_comments.comment_id = comments.comment_id
WHERE track_id=6 AND parent_id=-1 AND votes_comments.user_id=1
GROUP BY comments.comment_id
This query only returns one row since I only have a single row in votes_comments. I thought that left join would return results the way I want but apparently not. Any ideas how to get what I’m looking for?
I suspect the
WHEREclauseAND votes_comments.user_id=1is causing the problem.Read a tutorial on Joins and you’ll see that the result of your
LEFT JOINis a temporary table with two rows, and for each row, fields fromcomments JOIN usersand fromvotes_comments. If no matching record fromvotes_commentsexists, the fields in the temporary table are filled withNULLvalues.Your
WHEREclause,AND votes_comments.user_id=1, will fail becausevotes_comments.user_idisNULLin the rows ofuserwith no matchingvotes_commentsrecord.If what you actually want is to join to the row in
votes_commentswhat matches a specific user ID (e.g. ID=1), then yourONclause should be something like