如何与其他3个表多次连接同一个表?

时间:2015-03-11 00:32:41

标签: mysql join

我有4张桌子,匹配',' location',' team'并且' round'。具有以下结构:

  

匹配:location_id,team_one,team_two,round_id

     

位置:location_id,location_name,referee_name

     

团队:team_id,team_name

     

round :round_id,round_name

我想要做的是概述某一轮中所有位置的每场比赛,所以输出如下:

  

team_one_id,team_one_name,team_two_id,team_two_name,round_id,    location_name,裁判

我尝试的是:

SELECT * FROM `match` 
INNER JOIN `team` AS `team_one` ON `match`.`team_one` = `team_one`.`team_id`
INNER JOIN `team` AS `team_two` ON `match`.`team_two` = `team_two`.`team_id`
INNER JOIN `location` ON `match`.`location_id` = `location`.`location_id`

这种作品,但它只给了一个团队:团队最后一个叫(所以在这种情况下团队两个)。我不明白为什么它不起作用,因为我使用了别名。

我怎么能以上述方式加入这些表?

1 个答案:

答案 0 :(得分:0)

简短的回答:它应该可以工作,但是有时MySQL会因为我不知道的原因而对同名的列有问题(我之前已经看过这种行为)。最简单的补救措施是在查询中使用完整的alias.column:

SELECT 
    team_one.team_id AS team_one_id,
    team_one.team_name AS team_one_name,
    team_two.team_id AS team_two_id,
    team_two.team_name AS team_two_name,
    round_id,
    location_name,
    referee_name AS referee
FROM
    `match`
        INNER JOIN
    `team` AS `team_one` ON `match`.`team_one` = `team_one`.`team_id`
        INNER JOIN
    `team` AS `team_two` ON `match`.`team_two` = `team_two`.`team_id`
        INNER JOIN
    `location` ON `match`.`location_id` = `location`.`location_id`;