我以这种方式从postgres中的2个表中选择数据:
SELECT matches.id id, first_team_id T1, second_team_id T2, name
FROM matches
JOIN teams ON matches.first_team_id = teams.id
UNION
SELECT matches.id id, first_team_id T1, second_team_id T2, name
FROM matches
JOIN teams ON matches.second_team_id = teams.id
id T1 T2 name
1 1 2 Team1
1 1 2 Team2
2 1 3 Team2
2 1 3 Team1
id T1 T2 name1 name2
1 1 2 Team1 Team2
2 1 3 Team2 Team1
我需要最简单的方法来做到这一点。我在类似的问题中看到了一些解决方案,但我没有用它们来管理。请帮帮我
答案 0 :(得分:1)
你可以通过两个连接做你想要的事情:
select m.id, m.first_team_id, m.second_team_id, t1.name, t2.name
from matches m join
teams t1
on m.first_team_id = t1.id join
teams t2
on m.second_team_id = t2.id;