SQL left connection data becomes less

 

      Some time ago, a classmate encountered a problem when writing SQL: two SQL connections seemed to be the same, but the number of them was different. The reason is that the where condition after the left connection filters the data, making the data less. The two pieces of sql are as follows:

select count(1)
  from (select *
          from KXAPP.I_CASH_LOAN_WHITELIST_C2_V_NEW b
         where b.BG_DT < '20180820'
           and b.EN_DT >= '20180904') gh
  left join (select *
               from KXAPP.I_CASH_LOAN_WISH_SCORE
              where busi_dt = '20180820') hg
    on gh.loan_no = hg.loan_no
select count(1)
  from KXAPP.I_CASH_LOAN_WHITELIST_C2_V_NEW b
  left join KXAPP.I_CASH_LOAN_WISH_SCORE c
    on b.loan_no = c.loan_no
 where b.BG_DT < '20180820'
   and b.EN_DT >= '20180904'
   and busi_dt = '20180820') hg

     At first glance, there seems to be no difference between the two sql sections. The first one is to first fetch the sub-table through the condition and then to link; the second one is to link first and then filter after passing the condition. After statistics, it is found that the amount of data on the top is more than that on the bottom.

    In fact, these two links are different. In the first link mode, the main table is gh; in the second link mode, the main table is b. The reason why the amount of data in the second link method is less than that in the first link method is that where is added after the link to filter the link results.

    Here is an example to illustrate:

The structure of Table A is as follows:

 

The structure of Table B is as follows: 

select *
  from (select 1 as a, 2 as b
          from dual
        union all
        select 2 as a, 2 as b from dual) a
  left join (select 3 as a, 2 as b
               from dual
             union all
             select 2 as a, 2 as b from dual) b
    on a.a = b.a
   and b.a = 1;

select *
  from (select 1 as a, 2 as b
          from dual
        union all
        select 2 as a, 2 as b from dual) a
  left join (select 3 as a, 2 as b
               from dual
             union all
             select 2 as a, 2 as b from dual) b
    on a.a = b.a
 where b.a = 1;

 

Guess you like

Origin blog.csdn.net/lz_peter/article/details/83185909
Recommended