Kingsley Simon Kingsley Simon - 1 year ago 66
MySQL Question

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


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

So this is my query

SELECT COUNT( 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?


Answer Source

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

SELECT COUNT( AS count_all, cs.case_status AS counted 
FROM case_statuses cs LEFT OUTER JOIN 
     referrals r
     ON r.case_status_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.