Reputation: 60
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
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
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
Upvotes: 0
Views: 570
Reputation: 17606
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
Upvotes: 1
Reputation: 2382
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`
Upvotes: 1