简体   繁体   English

MySQL:从匹配id的其他表中获取多个数据

[英]MySQL: Get multiple data from other table matching the ids

I have two table one is battle and second is user the table structure and records in the tables are like below The user_id and competitor_id are the ids from user table 我有两个表一个是战斗,第二个是用户表结构,表中的记录如下所示user_id和competitor_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

I want to fetch the name user_id and competitor_id The Output Should look like below 我想获取名称user_id和competitor_id输出应如下所示

Output 产量

   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

Try this: 尝试这个:

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`

Two joins will do: 两个连接将执行:

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

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

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