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

前端 未结 6 1368
情话喂你
情话喂你 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:37

    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

    Updated query:

    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.

提交回复
热议问题