I have a SQL query that left joins a table in different ways depending on a condition.
SELECT m.id, u.first_name AS otherUser
FROM matches AS m
IF (u.id=m.user2I
Use this query:
SELECT m.id, u.first_name AS otherUser FROM matches AS m LEFT JOIN users AS u ON u.id = m.user1ID AND u.id=m.user2ID LEFT JOIN users AS u1 ON u1.id = m.user2ID WHERE m.user1ID=2 OR m.user2ID=2
SELECT m.id, u.first_name AS otherUser
FROM matches AS m
LEFT JOIN users AS u ON u.id = (CASE WHEN u.id=m.user2ID
THEN m.user1ID
ELSE m.user2ID
END)
WHERE m.user1ID=2 OR m.user2ID=2
Check this Source.
Also check this MYSQL Inner Join if statement . It might be helpful for you.