In a nutshell
GROUP_CONCAT() function lets you concatenate column values from multiple rows into a single string. It’s often used with
GROUP BY to join the list of column values for rows within each group.
An example should make it clearer.
Suppose you had a
students table like the below:
And you want to find the subjects each student is studying by returning the results like so:
You can use
GROUP_CONCAT to achieve get the desired result:
SELECT student_id, GROUP_CONCAT(subject) as subjects FROM students GROUP BY student_id;
GROUP_CONCAT() will separate each column value with a comma but you can also specify a different separator like so:
GROUP_CONCAT(subject SEPARATOR '; ') as subjects