表中有两次相同的外键

时间:2016-01-17 18:46:43

标签: mysql mariadb

我有一个足球比赛的数据库。保存匹配的表使用外键来存储团队(team1和team2 - 分别是host和guest)。我需要将结果与团队表中的结果相结合。

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

1 个答案:

答案 0 :(得分:3)

您必须两次加入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