You are viewing an old revision of this post, from June 30, 2016 @ 15:47:10. See below for differences between this version and the current revision.

MySql – Concatenate many rows into a single text string

I had an issue when I was trying to join two tables with one-to-many relationships. 

If there is a table called STUDENTS

SubjectID       StudentName
----------      -------------
1               Mary
1               John
1               Sam
2               Alaina
2               Edward

Result I expected was:

SubjectID       StudentName
----------      -------------
1               Mary, John, Sam
2               Alaina, Edward

 

* Solution:

 

In MySQL there is a function, GROUP_CONCAT(), which allows you to concatenate the values from multiple rows. Example:

SELECT 1 AS a, GROUP_CONCAT(name ORDER BY name ASC SEPARATOR ', ') AS people 
FROM users 
WHERE id IN (1,2,3) 
GROUP BY a

 

Revisions

  • June 30, 2016 @ 15:47:10 [Current Revision] by admin
  • June 30, 2016 @ 15:47:10 by admin
  • June 30, 2016 @ 15:46:13 by admin

Revision Differences

There are no differences between the June 30, 2016 @ 15:47:10 revision and the current revision. (Maybe only post meta information was changed.)

No comments yet.

Leave a Reply