有人可以帮助我理解当我向具有COUNT(*)LEFT JOIN的查询添加WHERE子句时发生的以下行为吗?
我有两张桌子:
TABLE 1: customers customer_id | name ------------------ 1 | Bob 2 | James 3 | Fred TABLE 2: orders order_id | customer_id | order_timestamp ---------------------------------------- 1000 | 1 | 2011-01-01 00:00 1001 | 1 | 2011-01-05 00:00 1002 | 2 | 2011-01-10 00:00
现在,以下查询告诉我每个客户下了多少订单:
select c.customer_id,count(o.order_id) from customers c left join orders o using (customer_id) group by 1 customer_id | count ------------------- 1 | 2 2 | 1 3 | 0
这很好但是如果我向查询添加一个WHERE子句,查询不再为没有下任何订单的客户输出零数,即使我正在进行LEFT JOIN:
select c.customer_id,count(o.order_id) from customers c left join orders o using (customer_id) where o.order_timestamp >= '2011-01-05' group by 1 customer_id | count ------------------- 1 | 1 2 | 1
现在,如果我将WHERE条件作为LEFT JOIN的一部分移动,如下所示,我会为没有下订单的客户取回零点数:
select c.customer_id,count(o.order_id) from customers c left join orders o on (c.customer_id = o.customer_id) and (o.order_timestamp >= '2011-01-05') group by 1
我很困惑为什么第二个查询不起作用,但第三个查询不起作用?有人可以请我解释一下吗?也不确定这是否重要,但我正在使用postgres.谢谢!