With the following tables
posts
- id
- post_id
- user_id
comments
- id
- post_id
- comment_id
- user_id
- deleted
replies
- id
- post_id
- reply_id
- user_id
- deleted
I am trying to get every comment and reply from each post.post_id and post.user_id=’x’ and the comment or reply is not deleted(0)
this is what i have tried
SELECT *
FROM posts p
LEFT JOIN comments c ON p.id=c.post_id
LEFT JOIN replies r ON p.id=r.post_id
WHERE p.user_id=$user_id
&& c.deleted='0' && r.deleted='0'
which does not work…
A post may have comments or not. Use
LEFT JOINinstead ofINNER JOIN.A post may have replies or not. Use
LEFT JOINinstead ofINNER JOINin that join too.When
LEFT JOINis used, a condition likeWHERE comments.deleted = 0that includes a field (from the right table (comments) in the LEFT JOIN), the LEFT JOIN is cancelled. So, we should put this condition in theONclause and not in theWHERE.Thinking more clearly, the above will show what the question describes but in cases with say, 4 comments and 3 replies, 12 rows will be returned (3×4). Which is probably not wanted. The following 2nd try does not have such issue.
I don’t see a
post.textorcomment.textorreply.textin the tables but anyway, you’ll get the idea. You can remove the 3textlines if not appropriate.The 0,1,2 stand for post, comment, reply.