0

我有两个表,一个是战斗,第二个是用户表结构和表中的记录如下所示 user_id 和竞争者_id 是用户表中的 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 和竞争者_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
4

2 回答 2

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`
于 2013-09-23T10:04:20.393 回答
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
于 2013-09-23T10:07:33.243 回答