5

我有一张篮球比赛桌和一张这样的篮球队桌:

MATCHES:
ID   |   HOME_TEAM_ID  |  AWAY_TEAM_ID | SCORE_HOME | SCORE_AWAY
----------------------------------------------------------------
1    |       20        |       21      |     80     |    110
2    |       12        |       10      |     96     |     90


TEAMS:
ID   |   NAME
-------------------------
20   |   BULLS
21   |   KNICKS

给定一个比赛 ID,我想同时检索比分和球队名称。如何进行 JOIN 以从 team 表中检索两个团队名称?

我试过了:

SELECT *
FROM matches AS m
JOIN teams AS t1 ON t.id = m.home_team_id
JOIN teams AS t2 ON ti.id = m.away_team_id
WHERE m.id = 1

...但是这里第二个 JOIN 语句的结果似乎覆盖了第一个语句的结果,所以我只得到一个名字:

[id] => 1
[score_home] => 80
[score_away] => 110
[name] => KNICKS

我也试过:

SELECT *
FROM matches AS m
JOIN teams AS t ON (t.id = m.home_team_id OR t.id = m.away_team_id)
WHERE m.id = 1

...返回两个结果:

[id] => 1
[score_home] => 80
[score_away] => 110
[name] => BULLS

[id] => 1
[score_home] => 80
[score_away] => 110
[name] => KNICKS

我想做一个返回类似这样的查询

[id] => 1
[score_home] => 80
[score_away] => 110
[name_home_team] => BULLS
[name_home_team] => KNICKS

那可能吗?

4

4 回答 4

9
SELECT
    Matches.ID,
    Matches.Score_Home,
    Matches.Score_Away,
    HomeTeam.Name Home_Team_Name,
    AwayTeam.Name Away_Team_Name
FROM
    Matches
    INNER JOIN Teams HomeTeam ON Matches.Home_Team_ID = HomeTeam.ID
    INNER JOIN Teams AwayTeam ON Matches.Away_Team_ID = AwayTeam.ID
于 2012-10-16T10:31:01.893 回答
2

你只需要用别名命名列名

SELECT m.ID,
       m.SCORE_HOME,
       m.SCORE_AWAY,
       t1.NAME as name_home_team,
       t2.NAME as name_home_team
FROM MATCHES AS m
JOIN teams AS t1 ON t1.id = m.home_team_id
JOIN teams AS t2 ON t2.id = m.away_team_id
WHERE m.id = 1
于 2012-10-16T10:34:54.977 回答
1
   select  m.ID,
           (select NAME from TEAM where id=m.HOME_TEAM_ID) HOME_TEAM_NAME,
           m.SCORE_HOME,
           (select NAME from TEAM where id=m.AWAY_TEAM_ID) AWAY_TEAM_NAME,    
           m.SCORE_AWAY 
    from 
    MATCHES m
    where m.ID=1
于 2012-10-16T10:29:37.527 回答
0

未经测试,应该可以工作:

select x.id, x.score_home, x.score_away, y.name as home_team, z.name as away_team
from matches x,
  (select name from teams where id = x.home_team_id)y,
  (select name from teams where id = x.away_team_id)z
where x.id = 1;
于 2012-10-16T10:31:32.970 回答