left join 限制条件放置位置导致的异常问题(易犯)

sql 1:

SELECT
    t1.id, t1.apply_no, t1.operator, t1.operate_result, t1.operate_task, t1.pipeline_id,
    t1.credit_amt, t1.audit_opinion, t1.add_doc_reason, t1.deal_time, t1.create_time,
    t1.update_time, t1.external_reason
FROM credit_apply_status_record t1
LEFT JOIN scp_business_exception_record t2
    on t1.operate_result = '03'
    and t1.apply_no = t2.business_no
    and date_format(t1.create_time, '%Y-%m-%d %H:%i:%s') = t2.remark
where   t1.create_time between #{startTime} and #{endTime} and t2.id is null

 

sql2:

SELECT
    t1.id, t1.apply_no, t1.operator, t1.operate_result, t1.operate_task, t1.pipeline_id,
    t1.credit_amt, t1.audit_opinion, t1.add_doc_reason, t1.deal_time, t1.create_time,
    t1.update_time, t1.external_reason
FROM credit_apply_status_record t1
LEFT JOIN scp_business_exception_record t2
    on t1.apply_no = t2.business_no
    and date_format(t1.create_time, '%Y-%m-%d %H:%i:%s') = t2.remark
where  t1.operate_result = '03' and t1.create_time between #{startTime} and #{endTime} and t2.id is null

 

2个sql的区别在于对t1的操作结果的筛选, sql1 放置在了left join on 条件中, 而sql2 放置在了where 条件内。

测试发现,sql1 的查询结果并未完成对t1的操作结果的筛选,大家在使用join 表关联的时候,不要想着都是筛选,都放join上也不是不可以的。  left join 的时候只是限制了左表和右表的关联条件,但是它并不会影响主表的查询数据结果。

 

posted @ 2022-12-06 15:26  guodaxia  阅读(132)  评论(0编辑  收藏  举报