具有1个Join和2个Where子句的Sql Query不返回所有记录

时间:2016-06-30 18:09:18

标签: mysql sql

那么伙计们,试着编写一个查询来获取project_id =的状态计数?和几个表格中的“新”状态,让我分解一下。

我有这三个表

Case_Status

id case_status   
1  New  
2  Failed
3. Accepted

推荐

id case_status_id project_id application_id 
1      1         1             20 
2      2         1             21

项目

id name 
1   project1 
2   project2

所以这是我的查询

SELECT COUNT(referrals.id) AS count_all, case_statuses.case_status AS counted 
    FROM "case_statuses" LEFT OUTER JOIN "referrals" ON "referrals"."case_status_id" = "case_statuses"."id" 
    WHERE "case_statuses"."deleted_at" IS NULL AND (case_statuses.case_status IN ('New') AND referrals.project_id = 1) 
    GROUP BY case_statuses.case_status;

这是我的结果

count_all  counted
1            New
1            Failed

但我期待这个结果

count_all  counted
    1            New
    1            Failed
    0            Accepted

有没有人知道我的查询有什么问题没有显示所有case_statuses的计数?

由于

3 个答案:

答案 0 :(得分:2)

第二个表格(left join中)的条件应该在on子句中:

SELECT COUNT(r.id) AS count_all, cs.case_status AS counted 
FROM case_statuses cs LEFT OUTER JOIN 
     referrals r
     ON r.case_status_id = cs.id AND r.project_id = 1
WHERE cs.deleted_at IS NULL AND cs.case_status NOT IN ('New') 
GROUP BY cs.case_status;

否则,WHERE子句将外连接转换为内连接。

答案 1 :(得分:0)

像这样更改您的查询

SELECT COUNT(referrals.id) AS count_all, case_statuses.case_status AS counted 
    FROM "case_statuses" LEFT JOIN "referrals" ON "referrals"."case_status_id" = "case_statuses"."id"  AND referrals.project_id = 1
    WHERE "case_statuses"."deleted_at" IS NULL AND case_statuses.case_status NOT IN ('New')  
    GROUP BY case_statuses.case_status;

答案 2 :(得分:0)

根据您的数据和预期结果,您只需要松开WHERE子句。

SELECT COUNT(referrals.id) AS count_all, case_statuses.case_status AS counted 
FROM case_statuses
      LEFT OUTER JOIN referrals ON referrals.case_status_id = case_statuses.id 
GROUP BY case_statuses.case_status;

有关详细信息,请参阅此fiddle