SQL,基于外键选择多个值,返回值

时间:2019-01-19 14:08:08

标签: mysql sql foreign-keys

如何根据团队表中的两个外键在查询,飞行员和副驾驶员中选择每个团队成员的姓名

表格:玩家

+----------------+-----------------+------+-----+---------+----------------+
| 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    |                | 
+----------------+-----------------+------+-----+---------+----------------+

表格:团队

+----------------+-----------------+------+-----+---------+----------------+
| 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    |                | 
+----------------+-----------------+------+-----+---------+----------------+

这是一个很好的数据库设置吗?

可能是SQL: Foreign Key With multiple child values的转发,但不能应用于我的

MCVE:https://www.db-fiddle.com/f/a2fCdy6RFqgReuL8FThhDP/2 结果应该是类似

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

2 个答案:

答案 0 :(得分:1)

似乎您需要两个简单的JOIN:

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

答案 1 :(得分:1)

尝试一下:

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