即使count()什么都不返回,如何选择所有行?

时间:2018-05-14 16:30:45

标签: mysql

我有两个简单的客户和订单列。如果count为零(或为null或其他),我想选择所有客户以及相应订单的数量甚至。以下工作仅返回有订单的客户:

select customers.id, count(orders.orderid) as total_orders from `xcart_customers` customers 
left join `xcart_orders` orders 
    on customers.id=orders.userid 
where orders.status in ('C', 'K') 
group by customers.id 

添加having total_orders=0没有帮助,因为未选择这些行。还尝试了ifnull和许多其他事情(左,右外连接),但没有运气。

1 个答案:

答案 0 :(得分:0)

以下是查询。

select customers.id, count(orders.orderid) as total_orders from `xcart_customers` customers 
left join `xcart_orders` orders 
    on customers.id=orders.userid and orders.status in ('C', 'K') 
group by customers.id