¿Cómo seleccionar todos los duplicados en MySQL?
Para seleccionar duplicados, puede utilizar la subconsulta. Primero creemos una tabla:
mysql> create table DemoTable
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(100)
-> );
Query OK, 0 rows affected (0.87 sec)
Inserte algunos registros en la tabla usando el comando insertar:
mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Name) values('Bob');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.12 sec)
Muestre todos los registros de la tabla usando la declaración de selección:
mysql> select *from DemoTable;
Producción
+----+--------+
| Id | Name |
+----+--------+
| 1 | John |
| 2 | Chris |
| 3 | John |
| 4 | David |
| 5 | Bob |
| 6 | Chris |
| 7 | Mike |
| 8 | Robert |
| 9 | Mike |
+----+--------+
9 rows in set (0.00 sec)
La siguiente es la consulta para seleccionar todos los duplicados:
mysql> select *from DemoTable
-> where Name in (select Name from DemoTable group by Name having count(*) > 1);
Producción
+----+-------+
| Id | Name |
+----+-------+
| 1 | John |
| 2 | Chris |
| 3 | John |
| 6 | Chris |
| 7 | Mike |
| 9 | Mike |
+----+-------+
6 rows in set (0.09 sec)