与缺少某些值的表联接

时间:2019-03-03 12:56:05

标签: sql join group-by

我有两个表,一个表包含客户及其ID,另一个表包含订单以及包含客户ID的订单信息。问题是,不是每个客户都下订单,所以当我加入时,他们相应的行会丢失

此外,我想对联接表执行group by子句以计算每笔订单花费的总金额,因此,即使我退出联接,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

输出: Table

所需的输出:

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

3 个答案:

答案 0 :(得分:2)

您想要外部联接。您应该从要保留所有行的表开始,然后使用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的结果。
  • 这引入了表别名,因此查询更易于编写和阅读。
  • 它从customers表开始,因为您需要所有顾客。而且,所有后续联接都是left join

答案 1 :(得分:0)

似乎您需要在right join之前使用alp_customer on ..

答案 2 :(得分:0)

您还可以通过更改表的顺序并使用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
相关问题