- 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
Check if the column values are the same among multiple records and set these records in a single row separated by a special character in MySQL
For this, you can use GROUP_CONCAT() along with DISTINCT. Let us first create a table −
mysql> create table DemoTable ( Id int, Subject varchar(40) ); Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100,'MySQL'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(100,'MongoDB'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(100,'Java'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(100,'MongoDB'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(101,'MySQL'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(101,'MySQL'); Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+---------+ | Id | Subject | +------+---------+ | 100 | MySQL | | 100 | MongoDB | | 100 | Java | | 100 | MongoDB | | 101 | MySQL | | 101 | MySQL | +------+---------+ 6 rows in set (0.00 sec)
Following is the query to check if the column values are the same among multiple records and set these records in a single row separated by a special character. The separator here is hyphen −
mysql> select Id,group_concat(distinct Subject separator '-') as Subject from DemoTable group by Id;
This will produce the following output −
+------+--------------------+ | Id | Subject | +------+--------------------+ | 100 | Java-MongoDB-MySQL | | 101 | MySQL | +------+--------------------+ 2 rows in set (0.04 sec)
Advertisements