- 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
Return a list from different rows into a single field with MySQL
For this, use GROUP_CONCAT(). Let us first create a table −
mysql> create table DemoTable2024 -> ( -> SubjectName varchar(20), -> StudentName varchar(20) -> ); Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2024 values('MySQL','Chris'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable2024 values('MySQL','David'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable2024 values('MongoDB','Bob'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable2024 values('Java','Sam'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable2024 values('MongoDB','Mike'); Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2024;
This will produce the following output −
+-------------+-------------+ | SubjectName | StudentName | +-------------+-------------+ | MySQL | Chris | | MySQL | David | | MongoDB | Bob | | Java | Sam | | MongoDB | Mike | +-------------+-------------+ 5 rows in set (0.00 sec)
Following is the query to return a list from different rows into a single field −
mysql> select SubjectName,group_concat(StudentName) -> from DemoTable2024 -> group by SubjectName;
This will produce the following output −
+-------------+---------------------------+ | SubjectName | group_concat(StudentName) | +-------------+---------------------------+ | Java | Sam | | MongoDB | Bob,Mike | | MySQL | Chris,David | +-------------+---------------------------+ 3 rows in set (0.06 sec)
Advertisements
To Continue Learning Please Login
Login with Google