I have two tables A and B and I have to perform left join on that with multiple cases in on condition. Is there any efficient way of doing this in big query or SQL.
select * from table_A A left join table_B B where [some condition OR some condition] on case1 A.column1 =B.column1 and A.column2= B.column2 and A.column3= B.column3 and A.column4= B.column4 and A.column5= B.column5 OR case2 A.column1 =B.column1 and A.column3= B.column3 and A.column4= B.column4 and A.column5= B.column5 OR case3 A.column1 =B.column1 and A.column2= B.column2 and A.column4= B.column4 OR case4 A.column1 =B.column1 and A.column3= B.column3 and A.column5= B.column5
Here my main motive is that for one row if my case1 matches than it will not go into other cases. Likewise it will work if first is not matches then it will check second, then third and it will get best possible one match. Here the cases will help that to get 100% of join between A and B table. In first cases we are checking all 5 fields of both table, but if some of the field are null than it will check other case and likewise it should work.
Advertisement
Answer
If I understand correctly, the general approach in SQL is multiple left join
s:
select a.*, coalesce(b1.col, b2.col, b3.col, b4.col) as col from table_A A left join table_B B1 on A.column1 = B1.column1 and A.column2 = B1.column2 and A.column3 = B1.column3 and A.column4 = B1.column4 and A.column5 = B1.column5 left join table_b B2 on B1.column1 is null and A.column1 = B2.column1 and A.column3 = B2.column3 and A.column4 = B2.column4 and A.column5 = B2.column5 left join table_b B3 on B2.column1 is null and A.column1 = B3.column1 and A.column2 = B3.column2 and A.column3 = B3.column3 left join table_b B4 on B3.column1 is null and A.column2 = B4.column2 and A.column4 = B4.column4