sql为同一行选择两次相同的字段

时间:2018-09-25 09:52:21

标签: sql

有两个表,一个用于团队比赛,另一个用于团队比赛。

竞赛表包含有关竞赛,得分,日期和teamId的信息。 (teamsId很重要)

| Competition | Team1 | Team2 | date
|      5      |  22   |   11  | 01-01-98|

团队表包含有关每个团队的信息,包括团队的名称。 (团队名称很重要)

| team Id | TeamName |
|    22   |Barcelona |
|    11   |Manchester|

查询:

SELECT competition, team1, team2, date, TeamName ta, TeamName as tb
FROM comp 
INNER JOIN teamname ON (team1 = Teamname)
WHERE team1 = 22 Limit 1;

到目前为止,我明白了:

| Competition | Team1 | Team2 | date    |ta        |   tb    |  
|      5      |  22   |   11  | 01-01-98|Barcelona |Barcelona|

我需要这个结果

| Competition | Team1 | Team2 | date    |ta        |tb       |
|      5      |  22   |   11  | 01-01-98|Manchester|Barcelona|

如何将一个团队名称返回给team1name,将另一个团队名称返回给team2name?不超过一排。

我宁愿不需要添加任何新的select或union所有,因为这只是实际查询的一小部分,在原始查询中,已经有很多select and union了。

2 个答案:

答案 0 :(得分:1)

只需JOIN两次!

SELECT competition, team1, team2, date, t1.TeamName ta, t2.TeamName as tb
FROM comp 
INNER JOIN team t1 ON (team1 = t1.teamid)
INNER JOIN team t2 ON (team2 = t2.teamid)
WHERE team1 = 22 Limit 1;

答案 1 :(得分:0)

使用加入队名两次

 select t3.Competition,t3.Team1,t3.Team2,t3.TeamName as team1,t2.TeamName as team2
from
(
    SELECT c.*,t1.TeamName

    FROM comp c
    left JOIN team t1 ON t1.teamid = c.Team1
) t3 left join team t2 ON t3.Team2 = t2.teamid


  Competition   Team1   Team2   team1          team2
           5     22          11     Barcelona   Manchester