Thursday, 30 August 2018

MySql Left Join does not keep the table on the left

So I have a simple data structure:

blog_entries
 id | category | title | body | desc| date

blog_comments
 id | entry_id | author | email | website | body | date

I am trying to LEFT JOIN blog_comments ON entry_id to get teh COUNT on comments for each entry. I only have two records in 'blog_entries' and none in 'blog_comments' ATM. For some reason when I run the query below, I only get one result back:
SELECT
    blog_entries.*,
    COUNT(blog_comments.id) AS comment_count
    FROM blog_entries
        LEFT JOIN blog_comments
            ON blog_entries.id = blog_comments.entry_id
I do not understand why my LEFT table is not being preserved.

Your left table is not being preserved, because according to: Group by functions
If you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.
You should use:
SELECT
    blog_entries.*,
    COALESCE( c.cnt, 0 ) as comment_count
FROM blog_entries
LEFT JOIN
  ( SELECT entry_id, COUNT(*) as cnt
    FROM blog_comments
    GROUP BY entry_id ) c
ON blog_entries.id = c.entry_id

0 comments:

Post a Comment