So I've got myself in a massive confused mess.
Basically, I have a little social network app and I have 4 different tables I need to combine into one view.
- Table 1 - User posts
- Table 2 - Users
- Table 3 - Likes
- Table 4 - Comments
I then need to return a list of posts, with the user details and then add columns for the number of likes and number of comments for each post respectively.
If a post doesn't have any likes or comments, then ideally we should show a Zero.
The query below joins everything up, but returns multiple rows of everything, as it is returning 1 row for each comment or like as well.
Anyone able to help me combine these together?
SELECT *
FROM app_posts AS p
LEFT JOIN app_comments AS c ON c.post_id = p.post_id
LEFT JOIN app_user AS u ON u.user_id = p.user_id
LEFT JOIN app_likes AS l ON l.post_id = p.post_id
WHERE u.user_banned = 0
AND p.post_public = 1
ORDER BY p.post_date DESC
Any help would be greatly appreciated!
Table columns are as follows;
app_likes
- like_id
- post_id
- user_id
- liked_date
app_comments
- comment_id
- comment_user_id
- post_id
- comment_body
- comment_date
app_posts
- post_id
- user_id
- post_content
- post_date
- post_public
app_user
- user_id
- user_first
- user_last
- user_avatar
- user_banned
An example of what is returned currently is as follows (chopped down for easiness)
You'll see the post_id is repeated multiple times.
What I want it to return is the post_id just once, and with the count of 'likes' and 'comments' in new columns (I don't know how to do this).
Simon

GROUP BYbut looks like you have repeated data, duplicated comment and dates so you may want to take a look to your query