2

Trying to create a SQL Server query based on a challenge match system. There are two tables that I want to join in the query: Users and ChallengeMatches.

The columns in the Users table are UserID, UserDisplayName

The columns in the ChallengeMatch table are ChallengeMatchID, ChallengerUserID, ChallengeeUserID

Of course, all ChallengeeUserID's and ChallengerUserID's are listed in the Users table as unique users. What I want the query to do is for each challenge match (row in the ChallengeMatch table), return the UserDisplayName of both of the challenge participants e.g. PlayerName1, PlayerName2.

Any help would be appreciated.

3
  • Honestly, did not know where to start in terms of matching the UserID with both the ChallengerUserID and the ChallengeeUserID to bring back the UserDisplayName for both. Commented Apr 29, 2014 at 22:01
  • 1
    Don't let what Borat discourage you you in asking questions. If that works make sure you give @citsonga the credit..
    – EricSSH
    Commented Apr 29, 2014 at 22:11
  • 1
    I added a SQL Fiddle to prove my answer works.
    – citsonga
    Commented Apr 29, 2014 at 22:55

2 Answers 2

7

You need to join the Users table twice. This should do the trick:

select 
    u1.UserDisplayName as [Challenger],
    u2.UserDisplayName as [Challengee]
from ChallengeMatch cm
left outer join Users u1
    on cm.ChallengerUserID = u1.UserID
left outer join Users u2
    on cm.ChallengeeUserID = u2.UserID
where cm.ChallengeMatchID = 2 /* specify value for relevant match */

Here is a SQL Fiddle with this example working.

0
2
Select * FROM 
    (
      SELECT 'Challenger' [Type]
          ,ChallengerUserID [UserID] 
      from ChallengeMatch 
      where ChallengeMatchID=2
     UNION ALL
      SELECT 'Challengee' [Type]
           ,ChallengeeUserID [UserID] 
      from ChallengeMatch 
      where ChallengeMatchID=2
          ) as c
Inner join Users u
  ON c.UserID=u.UserID

Returns results in slightly different form than @Citsonga, but works too.
I would consider storing information more like how the nested select looks in general (Except Type would be an Int foreign Key to the user types table that you would need) for easier joins of this nature. It would also allow you to expand to more than 1 challenger/e per match

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.