Mysql – How to write a query to get concatenated names of riders with the same weight

MySQLmysql-8.0

I want to retrieve a table with all Riders of the same Weight from a table named Rider, which is defined in this way:

CREATE TABLE Rider(
    name VARCHAR(30),
    weight REAL,
    PRIMARY KEY(name)
) ENGINE=innodb;

The data in it is:

Alan  55
Ana   55
Anne  50
Bill  65
David 60
Julia 55
Peter 65
Stan  60

I want a result like this:

50 Anne
55 Alan Ana Julia
60 David Stan
65 Bill Peter

I can't figure out how to do it. I can only manage to sort them all by weight with:

  SELECT weight, name 
    FROM Rider 
GROUP BY weight;

All help is greatly appreciated!

Best Answer

You're looking for GROUP_CONCAT:

SELECT weight, GROUP_CONCAT(name SEPARATOR ' ') as name_list
FROM Rider
GROUP BY weight