【问题标题】:Joining with table where some values are missing加入缺少某些值的表
【发布时间】:2019-03-03 12:56:05
【问题描述】:

我有两张表,一张包含客户及其 ID,另一张包含订单信息,包括客户 ID。问题是,并不是每个客户都下过订单,所以当我加入时,他们对应的行就不见了

此外,我想在 join 表上做一个 group by 子句来计算每个订单花费的总金额,所以即使我离开 join,group by 仍然会忽略没有任何订单的客户。我该如何解决这个问题?

我的查询:

select alp_customer.first, alp_customer.last, alp_customer.email, sum(alp_orderline.order_price)
from alp_orderline
inner join alp_orders on alp_orderline.order_id = alp_orders.order_id
inner join alp_customer on alp_orders.cust_id = alp_customer.cust_id
group by alp_customer.first, alp_customer.last, alp_customer.email

输出:

期望的输出:

Cindy - Jones - XXX@hotmail.com - 307.94
Mitch - Edwards - XXX@gmail.com - 64
Betty - Sorenson - XXX@yahoo.com - 231
Fourth - Guy - his mail - 0

【问题讨论】:

    标签: sql join group-by


    【解决方案1】:

    你想要外部连接。您应该从要保留所有行的表开始,然后使用left join

    select c.first, c.last, c.email, coalesce(sum(ol.order_price), 0)
    from alp_customer c left join
         alp_orders o
         on o.cust_id = c.cust_id left join
         alp_orderline ol
         on ol.order_id = o.order_id
    group by c.first, c.last, c.email;
    

    注意事项:

    • coalesce()NULL 结果替换为您似乎想要的0
    • 这引入了表别名,因此查询更易于编写和阅读。
    • 它从客户表开始,因为您需要所有客户。而且,所有后续连接都是left joins。

    【讨论】:

      【解决方案2】:

      看来您需要在alp_customer on .. 之前使用right join

      【讨论】:

        【解决方案3】:

        您也可以通过更改表格的顺序并使用LEFT JOIN 来做到这一点,如下所示。

        select alp_customer.first, alp_customer.last, alp_customer.email, sum(alp_orderline.order_price)
        from alp_customer
        left join alp_orderline on alp_orders.cust_id = alp_customer.cust_id
        left join alp_orders on alp_orderline.order_id = alp_orders.order_id
        group by alp_customer.first, alp_customer.last, alp_customer.email
        

        【讨论】:

          猜你喜欢
          • 2017-07-06
          • 1970-01-01
          • 1970-01-01
          • 2020-11-10
          • 1970-01-01
          • 1970-01-01
          • 2016-12-20
          • 2015-05-16
          • 1970-01-01
          相关资源
          最近更新 更多