MySQL 未从 NOT IN 函数返回值

MySQL not returning values from NOT IN function

我目前正在尝试编写一个查询,以显示至少有 5 个订单的客户和没有订单的客户。订单在他们自己的 table 中被跟踪,为了找到订单为 0 的客户,我们必须找到不在订单中的客户。下面是我尝试使用的查询,它 returns 同一个客户 5 次零订单。

with t1 as
 (select o.customerNumber, c.customerName, count(o.orderNumber) as FiveOrders
 from orders o join customers c on (o.customerNumber = c.customerNumber)
 group by o.customerNumber having count(o.orderNumber) = 5),
 t2 as
 (select distinct o.customerNumber, c.customerName, count(o.orderNumber) as NoOrders
 from orders o join customers c on (o.customerNumber = c.customerNumber)
 group by c.customerNumber not in(select customerNumber from orders))
 select distinct t1.customerNumber as FiveOrderNumber, t1.customerName as FiveOrderName,
 t2.customerNumber as NoOrderNumber, t2.customerName as NoOrderName
 from t1 join t2
 order by NoOrderName;

感谢任何帮助,谢谢!

如果错误只在第二个table到,我想是在使用之后 having with condition NOT IN 没有任何逻辑比较,我认为您可以轻松获得想要的结果,例如:

select distinct customerNumber, customerName, "0" as NoOrders 
from customers 
where customerNumber not in (Select customerNumber from orders)

如果 group by 很重要,您可以像在代码中一样使用它。

Zerofive可与LEFT JOIN

一起计算
select c.customerNumber, max(c.customerName) customerName, count(o.orderNumber) as FiveOrdersOrZero
from customers c
left join orders o on o.customerNumber = c.customerNumber
group by c.customerNumber 
having count(o.orderNumber) in ( 0, 5 )
order by FiveOrdersOrZero