如何联接指向单个主键的多个外键?

时间:2018-09-28 08:53:20

标签: mysql sql join foreign-keys

亲爱的

我下面有两个单独的sql语句。他们独立地工作良好。

select teams.team_name_eng AS "TNAME1"
from matches, teams
where matches.team1_uid = teams.tid;

select teams.team_name_eng AS "TNAME2"
from matches, teams
where matches.team2_uid = teams.tid  

如何将这些语句合并为一个语句?我希望输出为

TNAM1     TNAME2
-----     ------
playerA   PlayerB
playerC   playerD

注意:外键关系已经创建。

谢谢

7 个答案:

答案 0 :(得分:1)

您必须为表使用别名:

select teams_1.team_name_eng AS "TNAME1", teams_2.team_name_eng AS "TNAME2"
from matches, teams as teams_1, teams as teams_2
where matches.team1_uid = teams_1.tid
AND matches.team2_uid = teams_2.tid ;

答案 1 :(得分:1)

使用两次具有不同别名的联接

select t.team_name_eng AS "TNAME1", t1.team_name_eng AS "TNAME2"
from matches inner join teams t on matches.team1_uid = t.tid
inner join teams t1 on matches.team2_uid = t1.tid

答案 2 :(得分:1)

使用“加入”获取答案

componentDidMount(){
  this.props.switchLanguage(1, 'fr');
}

答案 3 :(得分:1)

基本加入 两次连接同一张表,每次使用不同的键:

select t.team_name_eng AS "TNAME1",
t2.team_name_eng AS "TNAME2"
from matches m
LEFT JOIN teams t ON m.team1_uid = t.tid
LEFT JOIN teams t2 ON m.team2_uid = t.tid
;

答案 4 :(得分:1)

在联接中两次使用teams表,一次用于team1_uid,另一次用于team2_uid

  select t.team_name_eng AS TNAME1,t1.team_name_eng as TNAME2
    from  matches m join  teams t
    on  m.team1_uid = t.tid
    join teams t1
        and m.team2_uid = t1.tid

答案 5 :(得分:1)

这是您可能正在寻找的查询。

rowData.stream()
       .collect(Collectors.groupingBy(r -> r.Case.getCaseId(), 
              Collectors.flatMapping(e -> e.getRuling().getPayments().stream(), 
                        Collectors.toSet())));

答案 6 :(得分:1)

请检查此查询

Select t.team_name_eng as"TNAME1", t2.team_name_eng as "TNAME2" from matches m  join teams t on m.team1_uid = t.tid join teams t2 on m.team2_uid = t2.tid