Get rows that have common value from the same table with different id in MySQL


For this, you can use GROUP BY HAVING clause. Let us first create a table −

mysql> create table DemoTable1467
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1467 values(100,'Chris');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1467 values(110,'David');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1467 values(120,'Mike');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1467 values(100,'Chris');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1467 values(130,'Carol');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1467 values(100,'Chris');
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1467;

This will produce the following output −

+------+-------+
| Id   | Name |
+------+-------+
|  100 | Chris |
|  110 | David |
|  120 | Mike  |
|  100 | Chris |
|  130 | Carol |
|  100 | Chris |
+------+-------+
6 rows in set (0.00 sec)

Here is the query to get rows that have common value from the same table with different id −

mysql> select Id,Name,count(*) as IdCount from DemoTable1467
   -> group by Id
   -> having IdCount > 2;

This will produce the following output −

+------+-------+---------+
| Id   | Name |  IdCount |
+------+-------+---------+
|  100 | Chris |       3 |
+------+-------+---------+
1 row in set (0.00 sec)

Updated on: 10-Dec-2019

752 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements