添加WHERE子句后,加入结果会感到困惑

时间:2010-07-22 20:58:49

标签: mysql

我正在尝试计算与每个诊所相关联的客户端数量,即使客户端数量为0,我也希望显示所有诊所。我的查询按预期工作,直到我抛出WHERE子句。

这是数据库表和查询​​的精简描述,以了解问题的本质。

客户表

client_id | health_clinic_id | accepted  
----------------------------------------
1           1                  1  
2           2                  NULL  
3           1                  1  

options_health_clinics表

health_clinic_id | health_clinic_name  
--------------------------------------
1                  South Valley  
2                  North Valley  
3                  East Valley  
4                  West Valley  

以下查询符合我的预期,即由于RIGHT JOIN,即使健康诊所的客户数为0,也会显示所有健康诊所。

SELECT  
    options_health_clinics.health_clinic_name,  
    COALESCE(COUNT(clients.health_clinic_id), 0) AS n_clients

FROM clients
    RIGHT JOIN options_health_clinics ON options_health_clinics.health_clinic_id = clients.health_clinic_id

GROUP BY options_health_clinics.health_clinic_id

一旦我抛出WHERE子句(下面)来过滤掉未接受的客户,只会显示非零数量的健康诊所。

WHERE clients.accepted = 1 

为什么会这样,我该如何解决?

谢谢, 米切尔

4 个答案:

答案 0 :(得分:0)

如果您需要非空的客户接受,那么您可以尝试这个 -

SELECT  
    options_health_clinics.health_clinic_name,  
    COALESCE(COUNT(clients.health_clinic_id), 0) AS n_clients

FROM clients
    RIGHT JOIN options_health_clinics ON options_health_clinics.health_clinic_id = clients.health_clinic_id

WHERE clients.accepted IS NOT NULL

GROUP BY options_health_clinics.health_clinic_id

答案 1 :(得分:0)

如果没有客户端,则clients.accepted为NULL。尝试:

WHERE clients.accepted = 1 OR clients.accepted IS NULL

答案 2 :(得分:0)

它会中断,因为您正确地将客户端连接到options_health_clinics,后者返回所有options_health_clinics行,但不是所有客户端。通过添加where子句clients.accepted = 1,您可以过滤掉所有没有客户端的诊所,因为对于所有这些行,<>的clients.accepted为null 1

答案 3 :(得分:0)

我认为你想将WHERE条件移动到ON状态。

RIGHT JOIN options_health_clinics
  ON options_health_clinics.health_clinic_id = clients.health_clinic_id
    AND clients.accepted = 1

在客户加入options_health_clinics之前,这将仅包括接受为1的客户。