Syntax error What's the most efficient way to pull data from MySQL so that it is formatted with duplicate values

What's the most efficient way to pull data from MySQL so that it is formatted with duplicate values



For this, you can use GROUP_CONCAT(). Let us first create a table −

mysql> create table DemoTable1561
   -> (
   -> StudentName varchar(20),
   -> Title text
   -> );
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1561 values('Adam','Learning Java');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1561 values('Bob','Learning C');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1561 values('Adam','Learning Spring and Hibernate Framework');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable1561 values('Carol','Learning MySQL from basic');
Query OK, 1 row affected (0.30 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1561;

This will produce the following output −

+-------------+-----------------------------------------+
| StudentName | Title                                   |
+-------------+-----------------------------------------+
| Adam        | Learning Java                           |
| Bob         | Learning C                              |
| Adam        | Learning Spring and Hibernare Framework |
| Carol       | Learning MySQL from basic               |
+-------------+-----------------------------------------+
4 rows in set (0.00 sec)

Here is the query to pull the data from MySQL so that it is formatted −

mysql> select StudentName,group_concat(Title separator ',') as FormattedOutput from DemoTable1561
   -> group by StudentName;

This will produce the following output −

+-------------+-------------------------------------------------------+
| StudentName | FormattedOutput                                       |
+-------------+-------------------------------------------------------+
| Adam        | Learning Java,Learning Spring and Hibernate Framework |
| Bob         | Learning C                                            |
| Carol       | Learning MySQL from basic                             |
+-------------+-------------------------------------------------------+
3 rows in set (0.00 sec)
Updated on: 2019-12-12T06:46:56+05:30

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements