双左联接忽略过滤器

时间:2019-06-23 19:36:35

标签: postgresql

我有一张桌子,上面有来访者,另一个是客户,还有另一个是位置(每个人都属于)。

我想显示每个位置的访问次数。预期的结果将是:

visit_count |  location_name
-----------------------------
     27     |   location_1
     1      |   location_2
     0      |   location_3

这是我的查询

SELECT COUNT(visits.visit_date) as visit_count, locations.location_name FROM locations 
LEFT JOIN VISITS ON locations.location_name = visits.location_checkin
LEFT JOIN customer ON visits.cust_id = customer.cust_id
WHERE locations.group_id = 1 AND customer.adm = false AND customer.super_adm = false
GROUP BY locations.id

但是结果只给了我

visit_count |  location_name
-----------------------------
     27     |   location_1
     1      |   location_2

这是正确的数据,但是零访问次数会擦除该位置。我试着把 customer.adm = false and customer.super_adm = false位于客户的左侧联接上,但是列出了所有三个位置,但忽略了对虚假陈述的过滤。

2 个答案:

答案 0 :(得分:2)

您需要将条件移至ON类别:

SELECT COUNT(customer.cust_id) as visit_count, locations.location_name 
FROM locations 
LEFT JOIN VISITS ON locations.location_name = visits.location_checkin 
LEFT JOIN customer ON visits.cust_id = customer.cust_id 
      AND customer.adm = false 
      AND customer.super_adm = false
WHERE locations.group_id = 1 
GROUP BY locations.id, locations.location_name -- here added location_name to match SELECT

如果在外部表列引用上使用WHERE,它将像普通INNER JOIN一样工作

答案 1 :(得分:0)

使用左联接,您不应该在..(在内部联接中)使用左表列。 而是将这些条件添加到相关的on子句

SELECT COUNT(visits.visit_date) as visit_count, locations.location_name 
FROM locations 
LEFT JOIN VISITS ON locations.location_name = visits.location_checkin
LEFT JOIN customer ON visits.cust_id = customer.cust_id  
       AND customer.adm = false AND customer.super_adm = false
WHERE locations.group_id = 1 
GROUP BY locations.id
相关问题