如何使用 Count 函数连接三个表以使 Return 结果也为零?

How to Join Three Tables with Count Function to Return Zero Results Too?

我有这个查询,有三个表(发票,customer_addresses,国家),我想return每个国家的销售额,有些国家没有销售额,所以我想将 return 归零为 sales_count,而不是将它们从结果中排除。

SELECT c.name,c.iso_code,c.id as country_id, COUNT(*) as sales_count ,SUM(a.total_due) as gross
        FROM `invoices` a
            JOIN `customer_addresses` b
            ON b.`customer_id` = a.`customer_id`
            JOIN `countries` c
            ON c.`id` = b.`country_id`
        WHERE  a.`status` = 'Paid' AND a.`deleted` ='No'
        GROUP BY c.name

示例数据:

发票

id   | total_due | customer_id
1    |    25     |      5
2    |    45     |      7

customer_addresses

id |    address    | customer_id | country_id
5  |  some address | 1           |    3
7  |  some address | 2           |    4

国家

id |       name     | iso_code 
3  | USA            | US
4  | United Kingdom | UK
5  | France         | Fr

您可以使用 right join 代替 (inner) join,但它用得不多,而且通常被认为可读性差。

因此,您可以对 table 使用 left join,并将 country 作为第一个 table。使用 left join,即使在连接的 table 中没有匹配的行,您仍然会得到一个结果。对 count 的调用也略有改变。 count(*) 将 return 只是行计数,因此对于没有发票的国家/地区,它将 return 1count(invoice_id) 仅计算那些 invoice_id is not null 的行,因此对于没有销售的国家/地区 return 0

SELECT 
  c.name, c.iso_code, c.id as country_id, 
  COUNT(a.invoice_id) as sales_count,
  SUM(a.total_due) as gross
FROM 
  `countries` c
  LEFT JOIN `customer_addresses` b
    ON c.`id` = b.`country_id`
  LEFT JOIN `invoices` a
    ON b.`customer_id` = a.`customer_id`
    AND a.`status` = 'Paid' 
    AND a.`deleted` ='No'
GROUP BY c.name