所以,我有一个用户表和一个订单表。orders表通过用户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
我的问题是它不会返回在orders表中没有记录的用户。理想情况下,我希望看到所有客户,并为没有下订单的用户显示0(甚至可以为空)。任何帮助都将不胜感激。
最佳答案
这是因为您有一个左连接,但随后将左表放在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
关于mysql - 无法查询零记录的联接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54755903/