How can I substitute a left join in SQL

前端 未结 3 1462
情话喂你
情话喂你 2020-12-30 14:30

Can anyone tell me how can I write the equivalent of a left join without really using left joins.

Select * from a left join b on a.name = b.name.
         


        
3条回答
  •  [愿得一人]
    2020-12-30 14:59

    Although left outer joins are the recommended way of writing sql as compared to an alternative but still we can achieve left outer join by using union for the resultset. If we have two table Table1 and Table 2 then we can achieve this by the following -

    select
           A.Id, 
           A.Col1, 
           A.Col2, 
           A.Col3, 
           B.Id Col4, 
           B.Col1 Col5, 
           B.Col2 Col6, 
           B.Col3 Col7, 
           B.Col4 Col8
    from   Table1 A, Table2 B
    where  A.Id = B.Id
    
    union all
    
    select
           A.Id, 
           A.Col1, 
           A.Col2, 
           A.Col3, 
           null as Col4, 
           null as Col5, 
           null as Col6, 
           null as Col7, 
           null as Col8
    from   Table1 A
    where  not exists(select 1 from Table2 B where B.Id = A.Id)
    

    This will help achieve the same result but because of the use of Union there could be some performance problems in case the tables are large.

提交回复
热议问题