When left join fails then due to vlu.status=1 query does not return anything.
I want result even if left join fails.
If i remove vlu.status=1 then it returns right result, but i have to use vlu.status=1 when left join does not fails.
select vb.first_name,vb.last_name,DATE_FORMAT(vb.created_date,'%m-%d-%Y') as Created_On,
concat(la.first_name,' ',la.last_name) as Loan_Agent, vl.loan_number,
count(vs.id) as Num_Deliveries from vid_borrowers vb
inner join vid_loans vl on vl.borrower_id= vb.id
left join vid_delivery_schedules vs on vs.borrower_id = vb.id
left join vid_loan_agents la on la.id=vl.loan_officer_id
left join vid_users vlu on vlu.id=la.user_id
where vb.bank_id=6
AND STR_TO_DATE(vb.created_date, '%Y-%m-%d') between '2014-12-01' and '2014-12-16'
and vlu.status=1
group by vb.first_name, vb.last_name, la.first_name, la.last_name, vl.loan_number
Put the condition inside the join and remove it from the WHERE clause; doing so creates a NULL row if the condition fails before the WHERE gets involved.
...
left join vid_users vlu on vlu.id=la.user_id and vlu.status = 1
where vb.bank_id=6
AND STR_TO_DATE(vb.created_date, '%Y-%m-%d') between '2014-12-01' and '2014-12-16'
group by vb.first_name, vb.last_name, la.first_name, la.last_name, vl.loan_number
You could let the WHERE take care of it as well by checking for NULL values, but IMHO it's better to perform the filter as soon as possible.
The problem here is that by applying a LEFT JOIN and a WHERE filter is that the condition where the LEFT JOIN fails returns NULL for vlu.status, which is then filtered out in the WHERE (since the criteria is vlu.status = 1). You need to change either:
WHERE ...
AND (vlu.status = 1 OR vlu.status IS NULL) -- NULL for the Left Join
OR move the vlu.status filter into the LEFT JOIN criteria
LEFT JOIN vid_users vlu on vlu.id=la.user_id AND vlu.status = 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With