How to use a case statement to determine which field to left join on

巧了我就是萌 提交于 2019-12-22 05:25:15

问题


I have a query that needs to be able to left join a field at the right place given the condition that the field is equal to a variable.

Something like:

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

I think I am on the right track but I'm not sure how to put the query together. Thanks


回答1:


Something like this may work

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



回答2:


It seems you want this:

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

which can be simplified to:

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


来源:https://stackoverflow.com/questions/7599811/how-to-use-a-case-statement-to-determine-which-field-to-left-join-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!