Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MySQL query to list all the items in a group in one record?
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)
Advertisements
