Use MySQL to find duplicates and display in a single line


For this, you can use GROUP_CONCAT() along with GROUP BY clause. Both are used to group concat duplicates and display in a single line. Let us first create a table −

mysql> create table DemoTable
(
   StudentFavouriteSubject varchar(40),
   StudentName varchar(40)
) ;
Query OK, 0 rows affected (0.75 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('MySQL','Chris');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('MongoDB','Bob');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('MySQL','Sam');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Java','Mike');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('C','Carol');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('MongoDB','John');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------------------------+-------------+
| StudentFavouriteSubject | StudentName |
+-------------------------+-------------+
| MySQL                   | Chris       |
| MongoDB                 | Bob         |
| MySQL                   | Sam         |
| Java                    | Mike        |
| C                       | Carol       |
| MongoDB                 | John        |
+-------------------------+-------------+
6 rows in set (0.00 sec)

Following is the query to find duplicates and display in a single line −

mysql> select group_concat(StudentName),StudentFavouriteSubject from DemoTable
group by StudentFavouriteSubject;

This will produce the following output −

+---------------------------+-------------------------+
| group_concat(StudentName) | StudentFavouriteSubject |
+---------------------------+-------------------------+
| Carol                     | C                       |
| Mike                      | Java                    |
| Bob,John                  | MongoDB                 |
| Chris,Sam                 | MySQL                   |
+---------------------------+-------------------------+
4 rows in set (0.00 sec)
raja
Published on 09-Oct-2019 15:32:03
Advertisements