如何使用case语句来确定要连接的字段

时间:2011-09-29 15:37:27

标签: mysql left-join case

我有一个查询,需要能够在正确的位置连接一个字段,条件是该字段等于变量。

类似的东西:

CASE WHEN challenges.userID = $var
LEFT JOIN challengesRead ON challenges.userID = challengesRead.userID
CASE WHEN challenges.opponentID = $var
LEFT JOIN challengesRead ON challenges.opponentID = challengesRead.userID

我认为我走在正确的轨道上,但我不确定如何将查询放在一起。 感谢

2 个答案:

答案 0 :(得分:9)

这样的事可能有效

LEFT JOIN challengesRead 
ON challenges.userID = CASE 
WHEN challenges.userID = $var THEN challengesRead.userID 
WHEN challenges.opponentID = $var THEN challenges.opponen END

答案 1 :(得分:0)

看来你想要这个:

LEFT JOIN challengesRead 
  ON CASE WHEN challenges.userID = $var
            THEN challenges.userID 
          WHEN challenges.opponentID = $var
            THEN challenges.opponentID
     END = challengesRead.userID

可以简化为:

LEFT JOIN challengesRead 
  ON $var = challengesRead.userID
  AND ( challenges.userID = $var
     OR challenges.opponentID = $var
      )