MySQL - Counting rows and left join problem

前端 未结 2 1973
一向
一向 2021-02-13 19:28

I have 2 tables, campaigns and campaign_codes:

campaigns: id, partner_id, status

campaign_codes: id, code, status

I want to get a count of all campaign_c

相关标签:
2条回答
  • 2021-02-13 19:57
    SELECT 
        c.id AS campaign_id, 
        COUNT(cc.id) AS code_count
    FROM 
        campaigns c
    LEFT JOIN campaign_codes cc on cc.campaign_id = c.id
        AND c.partner_id = 4
        AND cc.status = 0
    GROUP BY c.id
    
    0 讨论(0)
  • 2021-02-13 20:06

    I'd opt for something like:

    SELECT 
        c.id AS campaign_id, 
        COUNT(cc.id) AS code_count
    FROM 
        campaigns c
    LEFT JOIN campaign_codes cc on cc.campaign_id = c.id
    AND cc.status = 0 -- Having this clause in the WHERE, effectively makes this an INNER JOIN
    WHERE c.partner_id = 4
    GROUP BY c.id
    

    Moving the AND to the join clause makes the join succeed or fail, crucially keeping resulting rows in where there is no matching row in the 'right' table.

    If it were in the WHERE, the comparisons to NULL (where there is no campaign_code) would fail, and be eliminated from the results.

    0 讨论(0)
提交回复
热议问题