我有2个表格,广告系列和广告系列代码:
广告系列:id,partner_id,status
campaign_codes:id,code,status
我想了解所有广告系列的所有广告系列代码的计数WHERE campaign_codes.status等于0或广告系列没有campaign_codes记录。
我有以下SQL,但当然WHERE语句会删除那些在campaign_codes中没有相应记录的广告系列(我希望这些广告系列也包含零点广告系列代码)
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
WHERE c.partner_id = 4
AND cc.status = 0
GROUP BY c.id
答案 0 :(得分:20)
我会选择以下内容:
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
将AND
移动到join子句会使连接成功或失败,关键是将结果行保留在“右”表中没有匹配行的位置。
如果它在WHERE
中,则与NULL(没有campaign_code)的比较会失败,并从结果中删除。
答案 1 :(得分:3)
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