- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MySQL query to concatenate all the values in each row based on the common matching ID
Let us first create a table −
mysql> create table DemoTable ( StudentId int, StudentFirstName varchar(100), StudentLastName varchar(100) ); Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(1000,'Adam','Smith'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(1000,'John','Doe'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(1000,'David','Miller'); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+------------------+-----------------+ | StudentId | StudentFirstName | StudentLastName | +-----------+------------------+-----------------+ | 1000 | Adam | Smith | | 1000 | John | Doe | | 1000 | David | Miller | +-----------+------------------+-----------------+ 3 rows in set (0.00 sec)
Following is the query to concatenate all the values in each row based on the common matching ID −
mysql> select StudentId,group_concat(StudentFirstName),group_concat(StudentLastName) from DemoTable group by StudentId;
This will produce the following output −
+-----------+--------------------------------+-------------------------------+ | StudentId | group_concat(StudentFirstName) | group_concat(StudentLastName) | +-----------+--------------------------------+-------------------------------+ | 1000 | Adam,John,David | Smith,Doe,Miller | +-----------+--------------------------------+-------------------------------+ 1 row in set (0.00 sec)
Advertisements