简体   繁体   中英

Sql Query with 1 Join and 2 Where Clauses not returning all records

So guys, trying to write a query to get the count of statuses where project_id = ? and statuses in 'New' from a couple of tables so let me break it down.

I have these three tables

Case_Status

id case_status   
1  New  
2  Failed
3. Accepted

Referral

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

Project

id name 
1   project1 
2   project2

So this is my query

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;

This is my result

count_all  counted
1            New
1            Failed

But I am expecting this result instead

count_all  counted
    1            New
    1            Failed
    0            Accepted

Does anyone know what's wrong with my query that isnt showing count for all the case_statuses?

Thanks

Conditions on the second table (in a left join ) should be in the on clause:

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;

Otherwise, the WHERE clause turns the outer join into an inner join.

change your query like this

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;

Given your data and the expected result you just need to loose the WHERE clause.

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;

See this fiddle for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM