Mysql 多个ID为的列的SQL联接
我有两个SQL表。第一个表存储了运动员的id和姓名列表。例如:Mysql 多个ID为的列的SQL联接,mysql,sql,join,Mysql,Sql,Join,我有两个SQL表。第一个表存储了运动员的id和姓名列表。例如: athlete_id | first_name | last_name -----------|------------|---------- 1 | Matthew | Reese 2 | Tiffanie | Renz 3 | Tom | Dow event_id | lane1_athlete_id | lane2_athlete_id | lan
athlete_id | first_name | last_name
-----------|------------|----------
1 | Matthew | Reese
2 | Tiffanie | Renz
3 | Tom | Dow
event_id | lane1_athlete_id | lane2_athlete_id | lane3_athlete_id
---------|------------------|------------------|-----------------
1 | 1 | 15 | 24
2 | 18 | 2 | 4
3 | 78 | 50 | 3
event_id | lane1_athlete | lane2_athlete | lane3_athlete
---------|---------------|---------------|--------------
1 | Matthew Reese | Lesa Allain | Nicole Spiers
2 | Emmy Bartol | Tiffanie Renz | Louise Baier
3 | Zack Bui | Norah Flagg | Tom Dow
等等
第二个表存储径赛(冲刺)项目的条目,以及在每条车道上比赛的运动员的id。例如:
athlete_id | first_name | last_name
-----------|------------|----------
1 | Matthew | Reese
2 | Tiffanie | Renz
3 | Tom | Dow
event_id | lane1_athlete_id | lane2_athlete_id | lane3_athlete_id
---------|------------------|------------------|-----------------
1 | 1 | 15 | 24
2 | 18 | 2 | 4
3 | 78 | 50 | 3
event_id | lane1_athlete | lane2_athlete | lane3_athlete
---------|---------------|---------------|--------------
1 | Matthew Reese | Lesa Allain | Nicole Spiers
2 | Emmy Bartol | Tiffanie Renz | Louise Baier
3 | Zack Bui | Norah Flagg | Tom Dow
等等
我需要创建一个SQL查询,它将返回第二个表,但运动员ID将解析为运动员姓名。例如:
athlete_id | first_name | last_name
-----------|------------|----------
1 | Matthew | Reese
2 | Tiffanie | Renz
3 | Tom | Dow
event_id | lane1_athlete_id | lane2_athlete_id | lane3_athlete_id
---------|------------------|------------------|-----------------
1 | 1 | 15 | 24
2 | 18 | 2 | 4
3 | 78 | 50 | 3
event_id | lane1_athlete | lane2_athlete | lane3_athlete
---------|---------------|---------------|--------------
1 | Matthew Reese | Lesa Allain | Nicole Spiers
2 | Emmy Bartol | Tiffanie Renz | Louise Baier
3 | Zack Bui | Norah Flagg | Tom Dow
我想这涉及到一个表连接,但我无法理解正确的查询。任何帮助都将不胜感激。将第二个表连接到第一个表,三次:
SELECT
e.event_id,
CONCAT(a1.first_name, ' ', a1.last_name) AS lane1_athlete,
CONCAT(a2.first_name, ' ', a2.last_name) AS lane2_athlete,
CONCAT(a3.first_name, ' ', a3.last_name) AS lane3_athlete
FROM events e
LEFT JOIN athletes a1
ON e.lane1_athlete_id = a1.athlete_id
LEFT JOIN athletes a2
ON e.lane2_athlete_id = a2.athlete_id
LEFT JOIN athletes a3
ON e.lane3_athlete_id = a3.athlete_id;
在这种情况下,左侧外部联接比内部联接更安全,因为无效的运动员id将导致行随内部联接一起消失。@ChrisReynolds实际上,如果表设计正确,带有外键和主键,则甚至不可能在不存在的事件表中引用运动员。但是为了承认你的观点,我添加了左连接。非常感谢!我不确定是否需要重复连接,但似乎是这样。虽然下面有一个很好的解决方案,但我可能建议将数据库更改为3个表,而不是2个表——运动员、事件和事件运动员(可能有1个多表包含laneid列)。这样,您就不必在每次引入新车道时添加更多的柱。您的问题的解决方案可能会有所不同,但我相信这将是更规范化的方法。