2013-09-23 37 views
0

我有兩個表中的一個是戰鬥和第二是用戶的表結構和表中的記錄是像下面 的USER_ID和competitor_id是從用戶表的IDMySQL的:獲得從其他表的多個數據匹配的ID

A. Battle table 

    battle_id | user_id | competitor_id 
     1  | 1  | 5  
     2  | 3  | 4 
     3  | 2  | 3 

B. User table 

     ID | user_name 
     1 | ABC 
     2 | XYZ 
     3 | PQR 
     4 | MNO 
     5 | UVW 

我要取的名字USER_ID和competitor_id 輸出應該像下面

輸出

battle_id | user_id | competitor_id | user_name | competitor_name 
     1  | 1  | 5   | ABC  | UVW 
     2  | 3  | 4   | PQR  | MNO 
     3  | 2  | 3   | XYZ  | PQR 

回答

1

兩個連接就可以了:

SELECT b.battle_id, b.user_id, b.competitor_id, u1.user_name AS 'user_name', u2.user_name AS 'competitor_name' 
FROM `Battle` AS b 
JOIN `User` AS u1 ON u1.ID = b.user_id 
JOIN `User` AS u2 ON u2.ID = b.competitor_id 
1

試試這個:

SELECT `Battle`.`battle_id`,`Battle`.`user_id`,`Battle`.`competitor_id`,`User`.`user_name`,(SELECT `User`.`user_name` FROM `User` WHERE `Battle`.`competitor_id` = `User`.`ID`) AS `competitor_name` 
FROM `User` JOIN `Battle` ON (`Battle`.`user_id` = `User`.`ID`) 
ORDER BY `Battle`.`battle_id` 
相關問題