如何两次加入同一张桌子

时间:2019-05-20 17:02:08

标签: mysql sql

我想做的是从另一个表中切换一个具有相应名称的id。

团队:

 1 - team_01 
 2 - team_02

游戏:

 team_a     team_b   score_a   score_b
   1           2        30        40

我想要得到的是:
游戏:

 team_a     team_b   score_a   score_b
 team_01    team_02    30        40

我尝试:

    SELECT 
      games.id
    , games.score_team_a
    , games.score_team_b
    , games.time
    , games.category
    , games.team_a
    , games.team_b

    FROM games 

    LEFT JOIN teams t1 ON t1.id = games.team_a
    LEFT JOIN teams t2 ON t2.id = games.team_b

2 个答案:

答案 0 :(得分:1)

SELECT 
  games.id
, games.score_team_a
, games.score_team_b
, games.time
, games.category
, t1.<team_name> as team_a  -- reference the join tables
, t2.<team_name> as team_b

FROM games 

LEFT JOIN teams t1 ON t1.id = games.team_a
LEFT JOIN teams t2 ON t2.id = games.team_b

答案 1 :(得分:0)

您不需要左连接,我不明白为什么games表中的团队ID与teams表中的ID不匹配。
另外,如果只需要4列,为什么还要选择所有其他列?

   SELECT 
     t1.name team_a,
     t2.name team_b,
     g.score_a,
     g.score_b
   FROM games g
   INNER JOIN teams t1 ON t1.id = g.team_a
   INNER JOIN teams t2 ON t2.id = g.team_b