I need a query with posts-id, posts-title, posts-created_at, users-name, number-of-comments and likes-status. likes-status is 0 if none exists. Like this:
id |title |created_at |name |status |commentscount |
========================================================
1 |Hello 1 |2015-07-22 |Baker |-2 |2 |
2 |Hallo 2 |2015-07-23 |Tom |0 |0 |
My attempt:
SELECT p.id, p.title, p.created_at, u.name, COALESCE(c.body, 0) as commentscount, COALESCE(sum(l.status), 0) as status
FROM posts p
LEFT OUTER JOIN likes l ON l.post_id = p.id
LEFT OUTER JOIN users u ON u.id = p.user_id
LEFT OUTER JOIN comments c ON c.post_id = p.id
GROUP BY p.id, p.title, p.created_at, u.name, c.body
Result: id 1 should be summarized and commentscount should be 2. Status -2 should remain.
id |title |created_at |name |status |commentscount |
========================================================
1 |Hello 1 |2015-07-22 |Baker |-2 |Comment 1 | << issue
1 |Hello 1 |2015-07-22 |Baker |-2 |Comment 2 | << issue
2 |Hallo 2 |2015-07-23 |Tom |0 |0
users table
id |name |email |password |created_at |
====================================================
1 |Baker |[email protected] |UHds(& |2015-07-20 |
2 |Tom |[email protected] |ihj=)? |2015-07-21 |
posts table
id |user_id |title |created_at |
==================================
1 |1 |Hello 1 |2015-07-22 |
2 |2 |Hello 2 |2015-07-23 |
likes table
id |user_id |post_id |status |created_at |
===========================================
1 |1 |1 |-1 |2015-07-24 |
2 |2 |1 |-1 |2015-07-25 |
comments table
id |user_id |post_id |body |created_at |
==============================================
1 |1 |1 |Comment 1 |2015-07-28 |
2 |2 |1 |Comment 2 |2015-07-28 |