Group MySQL rows in an array by column value?


To group rows in an array, use GROUP_CONCAT() along with the ORDER BY clause. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int,
   -> FirstName varchar(20)
   -> );
Query OK, 0 rows affected (0.78 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(101,'John');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(102,'Bob');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(101,'David');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(101,'Adam');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(102,'Chris');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
|  101 | John      |
|  102 | Bob       |
|  101 | David     |
|  101 | Adam      |
|  102 | Chris     |
+------+-----------+
5 rows in set (0.00 sec)

Here is the query to group MySQL rows in an array by column value −

mysql> select Id,group_concat(FirstName separator ',') from DemoTable
   -> group by Id
   -> order by count(Id);

This will produce the following output −

+------+---------------------------------------+
| Id   | group_concat(FirstName separator ',') |
+------+---------------------------------------+
|  102 | Bob,Chris                             |
|  101 | John,David,Adam                       |
+------+---------------------------------------+
2 rows in set (0.00 sec)

Updated on: 11-Dec-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements