MySQL query to list all the items in a group in one record?

MySQLMySQLi Database

You can use GROUP_CONCAT() function to list all the items in a group in one record. Let us first create a table −

mysql> create table DemoTable
(
   ProductId int,
   ProductName varchar(40),
   ProductCategory varchar(40)
);
Query OK, 0 rows affected (0.67 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,'Product-1','1Product');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(101,'Product-2','2Product');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(100,'Product-1','3Product');
Query OK, 1 row affected (0.14 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+-------------+-----------------+
| ProductId | ProductName | ProductCategory |
+-----------+-------------+-----------------+
| 100       | Product-1   | 1Product        |
| 101       | Product-2   | 2Product        |
| 100       | Product-1   | 3Product        |
+-----------+-------------+-----------------+
3 rows in set (0.00 sec)

Following is the query to list all the items in a group in a single record −

mysql> select ProductId,group_concat(ProductCategory) AS `GROUP` FROM DemoTable group by ProductId;

This will produce the following output −

+-----------+-------------------+
| ProductId | GROUP             |
+-----------+-------------------+
| 100       | 1Product,3Product |
| 101       | 2Product          |
+-----------+-------------------+
2 rows in set (0.00 sec)
raja
Published on 29-Apr-2019 10:40:56
Advertisements