Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 257
Dave Chenell Avatar asked Sep 29 '11 15:09

Dave Chenell


1 Answers

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
like image 193
Raj More Avatar answered Nov 15 '22 06:11

Raj More