简体   繁体   English

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

[英]How to join multiple foreign keys that points to single primary key?

Dears, 亲爱的,

I have two separate sql statements below. 我下面有两个单独的sql语句。 Independently they work fine. 他们独立地工作良好。

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  

How can i combine those statements into one statement? 如何将这些语句合并为一个语句? I want the output to be 我希望输出是

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

Note: foreign-key relationships already created. 注意:已经创建了外键关系。

Thanks, 谢谢,

You have to use alias for your table : 您必须为表使用别名:

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 ;

Use join twice with different alias 使用具有不同别名的连接两次

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

Use Join to get the answer 使用加入获取答案

select teams1.team_name_eng AS "TNAME1",teams2.team_name_eng AS "TNAME2"
from matches
join teams as teams1 on teams1.tid = matches.team1_uid
join teams as teams2 on teams2.tid = matches.team2_uid

basic join join the same table twice, each time with a different key: 基本连接将同一表连接两次,每次使用不同的键:

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
;

use teams table in join 2 times , 1 for team1_uid and another for team2_uid 在联接中使用teams表2次,一次用于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

Here is the query you might be looking for. 这是您可能正在寻找的查询。

select teams.team_name_eng AS "TNAME1", teams.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 ;

请检查此查询

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM