How do I use an IF statement in an MySQL join query?

前端 未结 6 1370
情话喂你
情话喂你 2021-02-04 06:09

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         


        
6条回答
  •  粉色の甜心
    2021-02-04 06:41

    Specify the condition as part of the ON clause:

    SELECT m.id, u.first_name AS otherUser
    FROM matches AS m
    LEFT JOIN users AS u ON (u.id=m.user2ID and u.id = m.user1ID) or (u.id<>m.user2ID and u.id = m.user2ID) 
    WHERE m.user1ID=2 OR m.user2ID=2
    

    Another way to do the same thing:

    SELECT m.id, u.first_name AS otherUser
    FROM matches AS m
    LEFT JOIN users AS u ON IF(u.id=m.user2ID,u.id = m.user1ID,u.id = m.user2ID) 
    WHERE m.user1ID=2 OR m.user2ID=2
    

提交回复
热议问题