0

How to select each team member name in a query, pilot and copilot based on the two foreign keys in team table

Table: player

+----------------+-----------------+------+-----+---------+----------------+
| Field          | Type            | Null | Key | Default | Extra          |
+----------------+------------------------+-----+---------+----------------+
| id             | int(10) unsigned| NO   | PRI | NULL    | auto_increment | 
| name           | varchar(60)     | NO   |     | NULL    |                | 
| isPilot        | TINYINT(1)      | NO   |     | NULL    |                | 
| age            | int(4)          | NO   |     | NULL    |                | 
+----------------+-----------------+------+-----+---------+----------------+

table: team

+----------------+-----------------+------+-----+---------+----------------+
| Field          | Type            | Null | Key | Default | Extra          |
+----------------+-----------------+------+-----+---------+----------------+
| id             | int(10) unsigned| NO   | PRI | NULL    | auto_increment | 
| pilot_id       | int(10) unsigned| NO   | FK  | NULL    |                | 
| copilot_id     | int(10) unsigned| NO   | FK  | NULL    |                | 
+----------------+-----------------+------+-----+---------+----------------+

Is this a good database setup?

Might be a repost of SQL: Foreign Key With multiple child values , but can't apply it to mine

MCVE: https://www.db-fiddle.com/f/a2fCdy6RFqgReuL8FThhDP/2 Result should be something like

+----------------+-----------------+
| Pilot          | Co-Pilot        | 
+----------------+-----------------+
| player4Name    | player3Name     | 
| player2Name    | player1Name     |
+----------------+-----------------+

2 Answers2

1

It seems like you need two simple JOINs :

SELECT
    p.name AS pilot,
    cp.name AS copilot
FROM
    team AS t
    INNER JOIN player AS p on p.id = t.pilot_id
    INNER JOIN player AS cp on cp.id = t.copilot_id
GMB
  • 216,147
  • 25
  • 84
  • 135
1

Try this :

select p1.name, p2.name from player p1
join team t1 on p1.id = t1.pilot_id
join player p2 on p2.id = t1.copilot_id;

enter image description here

SKG
  • 164
  • 1
  • 2
  • 19