我想用不同的值mysql显示两次相同的列

时间:2014-01-07 09:15:30

标签: php mysql

从团队中选择*;

| team_name | team_id | 
| India     |       1 | 
| England   |       2 | 
| Germany   |       3 |
| Japan     |       4 |

从匹配中选择*;

| match_id | match_date | hometeam | awayteam | homescore | awayscore |
|        1 | 2014-06-24 |        1 |        2 |         3 |         0 |
|        2 | 2014-06-25 |        3 |        4 |         0 |         2 |

匹配表hometeamawayteam是团队表team_id

的外键

我想要一个显示homescoreawayscore以及team_names的选择

2 个答案:

答案 0 :(得分:3)

您必须将匹配表与团队表连接起来:

SELECT th.team_name as team_home, m.homescore, ta.team_name as team_away, m.awayscore
FROM matches m 
INNER JOIN teams th ON m.hometeam = th.team_id
INNER JOIN teams ta ON m.awayteam = ta.team_id

这是SqlFiddle

答案 1 :(得分:0)

另一个,整个匹配数据在一个选择...

select 
  m.*, 
  home.team_name as hometeam_name, 
  away.team_name as awayteam_name
from 
  matches m,
  teams home,
  teams away
where
  home.team_id = m.hometeam
  and
  away.team_id = m.awayteam
;

参见 SQLFIDDLE