Mysql – group_concat in separate columns

group byMySQL

I have a players table

id  name
--  ----
1   jack
2   john
3   mike
4   pikachu

And I have a matches table where these players can be matched together.

id pair_id player_id
-- ------- ---------
 1       1         1
 2       1         2
 3       2         3
 4       2         4

So I tried something like select group_concat(name) group by pair_id
The end results is something like:

names
---------
Jack,John

But what I like to is to get players in their own columns like:

p1   p2
---- ----
Jack John

How can I do that?

Best Answer

No group_concat needed, just joins:

select player1.name as p1, player2.name as p2
from matches m1
join players player1 on m1.player_id = player1.id
join matches m2 on m1.pair_id = m2.pair_id and m1.id != m2.id
join players player2 on m2.player_id = player2.id;