2016-01-17 86 views
1

我有一个足球比赛的数据库。保存匹配的表使用外键来存储团队(分别为team1和team2 - 主机和来宾)。我需要将结果与团队表中的结果结合起来。在表中两次相同的外键

match: 

+-----------------+------------------+------+-----+---------+----------------+ 
| Field   | Type    | Null | Key | Default | Extra   | 
+-----------------+------------------+------+-----+---------+----------------+ 
| match_id  | int(10) unsigned | NO | PRI | NULL | auto_increment | 
| championship_id | int(10) unsigned | YES | MUL | NULL |    | 
| team1_id  | int(10) unsigned | YES | MUL | NULL |    | 
| team2_id  | int(10) unsigned | YES | MUL | NULL |    | 
| factor_1  | decimal(4,2)  | YES |  | NULL |    | 
| factor_x  | decimal(4,2)  | YES |  | NULL |    | 
| factor_2  | decimal(4,2)  | YES |  | NULL |    | 
| goals_team_1 | tinyint(4)  | YES |  | NULL |    | 
| goals_team_2 | tinyint(4)  | YES |  | NULL |    | 
| match_date  | date    | YES |  | NULL |    | 
+-----------------+------------------+------+-----+---------+----------------+ 

team: 

+---------+------------------+------+-----+---------+----------------+ 
| Field | Type    | Null | Key | Default | Extra   | 
+---------+------------------+------+-----+---------+----------------+ 
| team_id | int(10) unsigned | NO | PRI | NULL | auto_increment | 
| name | varchar(32)  | YES |  | NULL |    | 
+---------+------------------+------+-----+---------+----------------+ 

我的猜测是,使用此查询,但它是无效的:

SELECT match.match_id, team.name, team.name, match.match_date 
FROM `match` 
INNER JOIN `team` 
ON match.team1_id=team.team_id, 
match.team2_id=team.team_id 
+2

使用两个团队而不是一个 – Ejaz

+0

您的查询不是无效的方式。它只会返回0行(除非你有一些团队与自己对抗的比赛)! –

回答

2

你必须加入team表两次,使用别名来区分每个加盟,就像这样:

SELECT match.match_id, team1.name, team2.name, match.match_date 
FROM `match` 
INNER JOIN `team` as team1 ON match.team1_id=team1.team_id 
INNER JOIN `team` as team2 ON match.team2_id=team2.team_id