SQL:如何在不覆盖结果的情况下对表的同一列进行多次连接?
Posted
技术标签:
【中文标题】SQL:如何在不覆盖结果的情况下对表的同一列进行多次连接?【英文标题】:SQL: How to make multiple joins to the same column of a table without overriding results? 【发布时间】:2012-10-16 10:22:55 【问题描述】:我有一张篮球比赛桌和一张这样的篮球队桌:
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
这可能吗?
【问题讨论】:
【参考方案1】: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
【讨论】:
【参考方案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
【讨论】:
【参考方案3】: 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
【讨论】:
【参考方案4】:未经测试,应该可以工作:
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;
【讨论】:
以上是关于SQL:如何在不覆盖结果的情况下对表的同一列进行多次连接?的主要内容,如果未能解决你的问题,请参考以下文章
如何在不使用 SQL 中的 PIVOT 函数的情况下进行透视?