Conditional Inner Join

后端 未结 4 686
醉梦人生
醉梦人生 2021-02-05 05:12

I want to be able to inner join two tables based on the result of an expression.

What I\'ve been trying so far:

INNER JOIN CASE WHEN Reg         


        
4条回答
  •  佛祖请我去吃肉
    2021-02-05 05:59

    So I had a scenario where there were three email columns in one table (don't ask why) and any of them could be null (or empty). In this example code I will just deal with a case where it is null.

    I had to join it to another table by any of the emails to retrieve the users firstname.

    Here is what worked

    select  
    
    m.email1,
    m.email2,
    m.email3, 
    m2.firstName
    
    from MyTable m
    
    left join MyOtherTable m2 on m2.Email = 
    case when m.email1 is null then 
    
        case when m.email2 is null then 
    
            case when m.email3 null then 
                'nonexistent@mydomain.com' -- i stopped here
            else m.email3 end
    
        else wm.email2 end
    
    else m.email1 end
    

    Obviously you would include further conditions like

    case when m.email1 is null or m.email1 = '' then ...
    

    To cover for empty values.

提交回复
热议问题