我在PHPMYADMIN中有这些表,我想要的是获取每个团队使用ID的名称,我一直在尝试使用LEFT JOIN,但它只返回1个团队,否则它将返回null
此表匹配
| match_id | HomeTeam | AwayTeam |
+------------------------------------------------
| 1 | 3 | 1 |
这是表团队
| team_id | team_name |
+----------------------------------------
| 1 | Manchester |
| 2 | Barcelona |
| 3 | Real Madrid |
这就是我想要SQL返回的结果
|match_id|HomeTeam|AwayTeam| Home_name | Away_name |
+-----------------------------------------------------
| 1 | 3 | 1 | Real Madrid | Manchester|
我一直在尝试使用这个SQL语句
SELECT `match.*`,`team_*` FROM `match`
LEFT JOIN `team` ON `match.HomeTeam` = `team.match_id`
LEFT JOIN `team` ON `match.AwayTeam` = `team.match_id`
WHERE `match.match_id` = 1
任何解决方案?
目前我正在使用这个PHP代码,但我觉得效率不高
$Query = 'SELECT * FROM match WHERE match_id = 1'
// excute Query //
foreach($match_array as $match)
{
$Query = 'SELECT FROM team WHERE team_id = '.$match['HomeTeam'].''
$home_team_name = somthing
$Query = 'SELECT FROM team WHERE team_id = '.$match['AwayTeam'].''
$away_team_name = something
}
答案 0 :(得分:2)
你必须使用表别名两次加入团队表。
SELECT match.*,team_home.*,team_away.* FROM match
LEFT JOIN team team_home ON match.HomeTeam = team_home.team_id
LEFT JOIN team team_away ON match.AwayTeam = team_away.team_id
WHERE match.match_id = 1
答案 1 :(得分:0)
您可以尝试使用别名以获取正确的信息:
SELECT `m`.`*`, `ht`.`name`, `at`.`name` FROM `match` m
LEFT JOIN `team` ht ON `m`.`HomeTeam` = `ht`.`match_id`
LEFT JOIN `team` at ON `m`.`AwayTeam` = `at`.`match_id`
WHERE `m`.`match_id` = 1
这可以给你你想要的东西