1

我有以下表格:

团队

+------+--------------+--------------+
| id   |  team_name   |  team_code   |
+------+--------------+--------------+
|  1   |  Wales       | WAL          |
|  2   |  England     | ENG          |
|  3   |  New Zealand | NZL          |
+------+--------------+--------------+

火柴

+------+-----------+-----------+
| id   |  team_a   |  team_b   |
+------+-----------+-----------+
|  1   |  WAL      | ENG       |
|  2   |  ENG      | NZL       |
|  3   |  WAL      | NZL       |
+------+-----------+-----------+

我知道联接是如何工作的,但我不知道如何通过从数据库Matched.id中获取两个团队的团队名称来查询Teams数据库。让我解释得更好

  • 对于每场比赛,我需要确定球队名称
  • 我会查询Matches.id
  • 所以对于匹配:1 我需要选择“威尔士”和“英格兰”

希望我已经足够清楚地解释了我的问题,但如果我还没有,请随时提出更多问题

4

3 回答 3

6

数据库结构对我来说似乎是“关闭”的。

您应该同时拥有team_ateam_b作为表主键的外键。Teams

然后,您可以加入 ID(两次)以获取全名。

比赛

+------+-----------+-----------+
| id   |  team_a   |  team_b   |
+------+-----------+-----------+
|  1   |  1        | 2         |
|  2   |  2        | 3         |
|  3   |  1        | 3         |
+------+-----------+-----------+

SELECT T1.team_name, T2.team_name
FROM Matches M
  INNER JOIN Teams T1
    ON M.team_a = T1.id
  INNER JOIN Teams T2
    ON M.team_b = T2.id
WHERE M.id = 1
于 2012-09-18T19:47:04.677 回答
1
Select
    matches.*, 
    teamA.team_name as TeamA_Name, 
    teamB.team_name as TeamB_Name
from matches
   inner join teams teamA on matches.team_a = TeamA.team_code
   inner join teams teamB on matches.team_b = TeamB.team_code
where 
   matches.id = 1
于 2012-09-18T19:47:31.823 回答
0
select 
    m.id, 
    t1.team_name, 
    t2.team_name
from 
    Matches m
    inner join Teams t1 on m.team_a = t1.team_code
    inner join Teams t2 on m.team_b = t2.team_code
于 2012-09-18T19:50:10.623 回答