Mysql 如果联接表没有特定的外部id,则返回Null

Mysql 如果联接表没有特定的外部id,则返回Null,mysql,sql,database,Mysql,Sql,Database,我有一个显示组织和卡片数量的查询,所以我加入了2个表, 这是一个疑问 SELECT o.organisation_id, organisation_name, IFNULL(COUNT(bus_operator_card_id),"--") num_cards FROM `organisation` o LEFT OUTER JOIN `bus_operator_cards` boc ON o.organisation_id = boc.organisation_id

我有一个显示组织和卡片数量的查询,所以我加入了2个表, 这是一个疑问

SELECT o.organisation_id, organisation_name, IFNULL(COUNT(bus_operator_card_id),"--") num_cards
FROM `organisation` o 
LEFT OUTER JOIN `bus_operator_cards` boc ON  o.organisation_id = boc.organisation_id 
WHERE o.org_type_id =5
AND boc.is_active = true GROUP BY o.organisation_id  ORDER BY o.organisation_id DESC;
这就是我得到的结果

-----------------------------------------------------
organisation_id | organisation_name   |   num_cards |
-----------------------------------------------------
   1            | Luxury Bus Services | 1  
   3            | Test test           | 5            
我想要的结果

-----------------------------------------------------
organisation_id | organisation_name   |   num_cards |
-----------------------------------------------------
   1            | Luxury Bus Services | 1           
   2            | Power tools         | --   
   3            | Test test           | 5                   

除了第一个表之外,所有表的条件都应该在
on
子句中,而不是
左连接的
WHERE

SELECT o.organisation_id, o.organisation_name, 
       COALESCE(CAST(COUNT(bus_operator_card_id) as CHAR), '--') as num_cards
FROM `organisation` o LEFT OUTER JOIN
     `bus_operator_cards` boc 
     ON o.organisation_id = boc.organisation_id AND boc.is_active = true 
WHERE o.org_type_id = 5
GROUP BY o.organisation_id
ORDER BY o.organisation_id DESC;
您的
WHERE
子句正在过滤掉将外部联接转换为内部联接的不匹配项

请注意,结果列是字符串,而不是数字。由于类型优先级规则,您需要将计数转换为字符串。但是,我建议对以下值使用
0
NULL

SELECT o.organisation_id, o.organisation_name, 
       COUNT(boc.bus_operator_card_id) as num_cards

给定列的名称,
0
对我来说比
'-'

更有意义,谢谢你的提示