我有一个包含足球比赛的数据库。保存比赛的表使用外键来存储团队(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
最佳答案
您必须加入 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
关于mysql - 同一个外键在表中出现两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34842190/