Mysql
 sql >> Database >  >> RDS >> Mysql

Come si usa un'istruzione IF in una query di join MySQL?

Specificare la condizione come parte della clausola ON:

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

Un altro modo per fare la stessa cosa:

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