2012-06-04 198 views
0

我有4個表格,如下所示;如何執行此操作?

tbl_UserInfo  DUMMY VALUES  DATATYPE  
UserID     1    Integer (PRIMARY KEY) 
UserName    A    Text   
FacebookID   10021556   Text   
EmailID    [email protected]  Text   
Facebook_EmailID [email protected]  Text   
Password   welcome123   Text   
Chips     100    Integer  
DeviceType    iphone   Text  



tbl_Game   DUMMY VALUES  DATA TYPE 
GameID     1    Integer  
Type     H or M   Text   
Complete    No    Text  



tbl_GamePlayer  DUMMY VALUES  DATA TYPE 
ID      1   Integer (PRIMARY KEY) 
GameID     1   Integer (FOREIGN KEY FOR GameID in tbl_Game) 
userid     1   Integer (FOREIGN KEY FOR UserID in tbl_UserInfo)  



tbl_Streaks   DUMMY VALUES  DATA TYPE 
ID      1   Integer 
GameID     1   Integer (FOREIGN KEY FOR GameID in tbl_Game) 
Player1    1   Integer (FOREIGN KEY FOR UserID in tbl_UserInfo) 
Player2    2   Integer (FOREIGN KEY FOR UserID in tbl_UserInfo) 
Streaks    2   Integer 

我想reslut作爲

{ 
Player1 = "A" 
Player2 = 'B" 
Streaks = 10 (between Player1 and Player2) 
Chips = 100 (for player1) 
Chips = 200 (for player2) 
Fbid= 124578 (for player1) 
Fbid = 784512 (for player2) 
} 

{ 
Player1 = "A" 
Player3 = 'C" 
Streaks = 15 (between Player1 and Player3) 
Chips = 100 (for player1) 
Chips = 450 (for player3) 
Fbid= 5654578 (for player1) 
Fbid = 7845512 (for player3) 
} 

{ 
Player1 = "A" 
Player4 = 'D" 
Streaks = 5(between Player1 and Player4) 
Chips = 100 (for player1) 
Chips = 208 (for player4) 
Fbid= 12898978 (for player1) 
Fbid = 78488512 (for player4) 
} 

我想和完整=「沒有」

顯示在用戶登錄(與他的其他球員的fbids,用戶名,芯片,條紋)的所有現有遊戲

注 - userid作爲參數傳遞和所有的球員都通過自己的用戶ID連接

+0

列{Player1,Player2,Player3,Player4,Player5}看起來像是一個重複組。也許你應該首先規範你的數據模型。 – wildplasser

+0

你有沒有看過,並理解,'JOIN'的美妙世界?如果不是,你是不是'看着'或'明白'?在後一種情況下,請發佈您迄今爲止創建的SQL查詢。 – jos

回答

1
SELECT Player1.UserName AS Player1_UserName, 
     Player2.UserName AS Player2_UserName, 
     tbl_Streaks.Streaks AS Streaks, 
     Player1.Chips  AS Player1_Chips, 
     Player2.Chips  AS Player2_Chips, 
     Player1.FacebookID AS Player1_FacebookID, 
     Player2.FacebookID AS Player2_FacebookID 
FROM tbl_Game 
    JOIN tbl_GamePlayer AS gPlayer1 ON gPlayer1.GameID = tbl_Game.GameID 
    JOIN tbl_GamePlayer AS gPlayer2 ON gPlayer2.GameID = tbl_Game.GameID 
           AND gPlayer1.UserID != gPlayer2.UserID 
    JOIN tbl_UserInfo AS Player1 ON gPlayer1.UserID = Player1.UserID 
    JOIN tbl_UserInfo AS Player2 ON gPlayer2.UserID = Player2.UserID 
    LEFT JOIN tbl_Streaks ON tbl_Streaks.GameID = tbl_Game.GameID 
         AND (tbl_Streaks.Player1, tbl_Streaks.Player2) IN (
          (Player1.UserID, Player2.UserID), 
          (Player2.UserID, Player1.UserID) 
          ) 
WHERE Player1.UserID = 1 AND tbl_Game.Complete = 'No' 

sqlfiddle上查看。

+0

@RKP:如果不是來自'tbl_Streaks.Streaks'的相應條目,結果集中的Streaks值應該是多少? – eggyal

+0

@RKP:如果不是'tbl_Streaks.Streaks',記錄在哪裏? – eggyal

+0

@RKP:因此,如果玩家A和玩家B在'tbl_Streaks'中沒有記錄,但是有一個遊戲中這些玩家都玩過了,您需要在結果集中記錄具有'Streaks'的玩家NULL的值? – eggyal