Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to perform left joins on multiple tables along with aggregate functions

SELECT 
posts.id,posts.user_id,
username, title,posts.body as post_body, posts.created_at, posts.is_open, posts.views as views, users.photoUrl,
COUNT(DISTINCT answers.id) as answer_count,
COUNT(DISTINCT comments.id) as comment_count,
COUNT (CASE answers.approved WHEN 1 THEN 1 ELSE null END) as correct_count,
GROUP_CONCAT(tagname) as tags
FROM posts 
LEFT JOIN posttag ON posts.id = post_id 
JOIN tags ON tag_id = tags.id 
JOIN users ON user_id = users.id 
LEFT JOIN answers ON answers.post_id = posts.id 
LEFT JOIN comments ON posts.id = comments.post_id 
WHERE posts.id = ?;

I am trying to query every post with its corresponding answers, comments and tags.

However in my query result, I get 8 tags when there are 4

The COUNT correct_count changes from from 1 to 4

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I get the correct data?

>Solution :

Use DISTINCT for correct_count and tags also:

.....................................
COUNT(DISTINCT CASE WHEN answers.approved THEN answers.id END) as correct_count,
GROUP_CONCAT(DISTINCT tagname) as tags
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading