MySQL - 加入2个表,其中2个id共同作为查询

时间:2014-03-16 11:44:34

标签: mysql sql

我有这个问题:

我的sql数据库看起来像这样:

table "uitslagen" :

id
teamid1
teamid2
uitslag

table "teams" :

id
name

我希望将teamid1和teamid2加入teams.id,以便我在比赛中获得每个团队的名称。

我想得到的是:

uitslagen.id | teamid1 AS teams.name | teamid2 AS teams.name | uitslagen.uitslag

示例:

1 | jong ajax | ado den haag | 2:1

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT
  U.id,
  T1.name as Team1_Name,
  T2.name as Team2_Name,
  U.uitslag
FROM uitslagen U
  JOIN teams T1
    ON U.teamid1 = T1.id
  JOIN teams T2
    ON U.teamid2 = T2.id

答案 1 :(得分:0)

加入teams表两次并使用不同的别名来区分它们

select u.id, 
       teamid1 AS t1.name,
       teamid2 AS t2.name,
       u.uitslag
from uitslagen as u
join teams as t1 on t1.id = u.teamid1
join teams as t2 on t2.id = u.teamid2