因此,我有一个用户表和一个订单表。订单表通过user_id列链接到用户表。我想做的是运行一个查询,以获取所有用户以及他们下的订单数量和订单总成本。这就是我所拥有的:
select count(orders.id) as order_count, sum(orders.total_cost) as total_spent, CONCAT_WS(", ", `last_name`, `first_name`) AS `customer_name`, users.id as user_id
from users
left join orders on users.id = orders.user_id
where orders.status != 'Canceled'
group by user_id
order by order_count asc
我的问题是,它不会返回在订单表中没有记录的用户。理想情况下,我想查看所有客户并为未下订单的用户显示0(即使为null也可以)。任何帮助将不胜感激。
答案 0 :(得分:1)
您快到了,只需要添加group by
语句
select
count(orders.id) as order_count,
sum(orders.total_cost) as total_spent,
CONCAT_WS(", ", `last_name`, `first_name`) AS `customer_name`,
users.id as user_id
from users
left join orders on users.id = orders.user_id and orders.status != 'Canceled'
group by `customer_name`, user_id
还请注意,如果进行左联接,并且需要在左联接表上添加约束,则需要将其放在on
子句中。
如果将左侧条件放在where子句中,则左联接将隐式转换为内部联接
答案 1 :(得分:1)
这是因为您有一个左联接,但是将左表放在了进行内部联接的where条件中。
这两个修复程序将条件放入了连接中:
select count(orders.id) as order_count, sum(orders.total_cost) as total_spent, CONCAT_WS(", ", `last_name`, `first_name`) AS `customer_name`, users.id as user_id
from users
left join orders on users.id = orders.user_id and orders.status != 'Canceled'
group by user_id
order by order_count asc
或测试是否为空
select count(orders.id) as order_count, sum(orders.total_cost) as total_spent, CONCAT_WS(", ", `last_name`, `first_name`) AS `customer_name`, users.id as user_id
from users
left join orders on users.id = orders.user_id
where coalesce(orders.status,'') != 'Canceled'
group by user_id
order by order_count asc