mysql - How to select all rows even when count() returns nothing?
问题描述
I have two simple columns for customers and orders. I want to select all customers and the number of appropriate orders even if count is zero (or null or whatever). The following ain't working and returns only customers which have orders:
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
Adding having total_orders=0
does not help, because those rows were not selected. Also tried ifnull
and many other things (left, right outer join), but no luck.
解决方案
这是查询。
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
推荐阅读
- .net-core - 顶部有菜单的 Blazor 模板
- typescript - 如何从谷歌的位置输入字段中选择一个项目
- python - 为什么 while(n) n = n>>1 循环不会以负 n 终止
- javascript - Onclick 事件在另一个函数的产品中不起作用
- ios - @Observable 模型更改未反映在视图中
- excel - CSV 到 Excel 不会丢失特殊字符
- json - 使用正则表达式从 json 字符串中提取值
- angular - Angular 通用视图页面源出现在 Mozilla 上,但不在 Chrome 上
- python - CUDA 问题 - 如何在 Win 10 中全新安装 CUDA 以解决 cudaGetDevice() 失败
- c# - 从 URL 加载 AssetBundle