简体   繁体   English

SQL Server:查询连接两个表

[英]SQL Server : Query Joining Two Tables

Trying to create a SQL Server query based on a challenge match system. 尝试基于挑战匹配系统创建SQL Server查询。 There are two tables that I want to join in the query: Users and ChallengeMatches . 我想在查询中加入两个表: UsersChallengeMatches

The columns in the Users table are UserID, UserDisplayName Users表中的列是UserID, UserDisplayName

The columns in the ChallengeMatch table are ChallengeMatchID, ChallengerUserID, ChallengeeUserID ChallengeMatch表中的列是ChallengeMatchID, ChallengerUserID, ChallengeeUserID

Of course, all ChallengeeUserID 's and ChallengerUserID 's are listed in the Users table as unique users. 当然,所有ChallengeeUserIDChallengerUserID都在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 eg PlayerName1 , PlayerName2 . 我希望查询执行的是每个挑战匹配( ChallengeMatch表中的行),返回两个挑战参与者的UserDisplayName ,例如PlayerName1PlayerName2

Any help would be appreciated. 任何帮助,将不胜感激。

You need to join the Users table twice. 您需要两次加入Users表。 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. 这是一个使用此示例的SQL小提琴。

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. 返回的结果与@Citsonga略有不同,但也有效。
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. 我会考虑更多地存储信息,就像嵌套选择看起来一般(除了Type将是你需要的用户类型表的Int外键),以便更容易地加入这种性质。 It would also allow you to expand to more than 1 challenger/e per match 它还允许您扩展到每场比赛超过1个挑战者/ e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM