如何在PostgreSQL中将两行合并为一行?
我以这种方式从postgres中的两个表中选择数据:如何在PostgreSQL中将两行合并为一行?,sql,postgresql,Sql,Postgresql,我以这种方式从postgres中的两个表中选择数据: 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
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
这就是我的桌子现在的样子:
这就是我需要的
我需要最简单的方法。我在类似的问题中看到了一些解决方案,但我没有设法解决它们。请帮助我通过两个连接,您可以做您想做的事情:
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;
id T1 T2 name1 name2
1 1 2 Team1 Team2
2 1 3 Team2 Team1
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;