[英]'where' condition fails when left join returns null
When left join
fails then due to vlu.status=1
query does not return anything. 当
left join
失败时,由于vlu.status=1
查询不返回任何内容。 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. 如果我删除
vlu.status=1
然后它返回正确的结果,但是当左连接没有失败时我必须使用vlu.status=1
。
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; 将条件放在连接中并将其从WHERE子句中删除; doing so creates a NULL row if the condition fails before the WHERE gets involved.
这样做会在WHERE参与之前条件失败时创建一个NULL行。
...
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. 你可以让WHERE通过检查NULL值来处理它,但恕我直言,最好尽快执行过滤器。
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
). 这里的问题是,通过应用
LEFT JOIN
和WHERE
过滤器, LEFT JOIN
失败的条件为vlu.status
返回NULL,然后在WHERE
过滤掉(因为标准是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 或者将vlu.status过滤器移动到LEFT JOIN条件
LEFT JOIN vid_users vlu on vlu.id=la.user_id AND vlu.status = 1
The coalesce
function takes a list of expressions and returns the first result that isn't null. coalesce
函数获取表达式列表并返回非null的第一个结果。 You can use it to replace nulls with a default value: 您可以使用它来使用默认值替换空值:
coalesce(vlu.status = 1, true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.