Skip to content
Advertisement

How to perform LEFT JOIN with condition

I want to perform something like this

SELECT  g.Name, g.emailID, g.phoneNo
FROM roomAllocation as ra
// if ra.guest_email is NOT NULL
LEFT JOIN Guests as g ON ra.guest_email = g.emailid
// else
LEFT JOIN Guests as g ON ra.guestPhoneNo = g.PhoneNo

Advertisement

Answer

If I understand correctly, you want to conditionally join to a table. I would recommend two left joins as in:

select t1.*,
       coalesce(ge.name, gp.name) as name
from table1 t1 left join
     table2 ge
     on t1.guest_email = ge.email_id left join
     table2 gp
     on t1.guest_phoneNo = gp.phoneNo and t1.guest_email is null;

Because it is the same table, you could also use or in the on clause:

select t1.*, g.*
from table1 t1 left join
     table2 g
     on t1.guest_email = geemail_id or
        (t1.guest_phoneNo = g.phoneNo and t1.guest_email is null);

However, or in an on clause usually kills performance.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement