且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在MySQL联接查询中使用IF语句?

更新时间:2023-10-06 11:36:40

将条件指定为ON子句的一部分:

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