0

Tengo una tabla con los siguientes registros 1 2 2 3 4 4 5 quiero hacer una consulta que solo me de como resultado 2 2 4 4

0

1 respuesta 1

2

Suponiendo que tu tabla luce similar a esto:

select * from names;
+----+-------+
| id | field |
+----+-------+
|  1 |     1 |
|  2 |     2 |
|  3 |     2 |
|  4 |     3 |
|  5 |     4 |
|  6 |     4 |
|  7 |     5 |
+----+-------+

Con la siguiente agregación agrupamos por el campo field y con having aplicamos una condición más (se repite más de una vez):

select field from names group by field having count(field) > 1;
+-------+
| field |
+-------+
|     2 |
|     4 |
+-------+

Para obtener el id de los que se repiten:

select * from names where field in (select field from names group by field having count(field) > 1);
+----+-------+
| id | field |
+----+-------+
|  2 |     2 |
|  3 |     2 |
|  5 |     4 |
|  6 |     4 |
+----+-------+

Para obtener los registros que no se repiten podemos realizarlo con la siguiente consulta:

select * from names where field in (select field from names group by field having count(field) = 1);
+----+-------+
| id | field |
+----+-------+
|  1 |     1 |
|  4 |     3 |
|  7 |     5 |
+----+-------+

Y para eliminarlos necesitamos usar una tabla temporal, ya que no podemos ejecutar delete con agregaciones sobre la misma tabla:

create temporary table temp select * from names where field in (select field from names group by field having count(field) = 1);

Después ejecutamos el delete:

delete from names where id in (select id from temp);

Por lo que la tabla queda de esta manera:

select * from names;
+----+-------+
| id | field |
+----+-------+
|  2 |     2 |
|  3 |     2 |
|  5 |     4 |
|  6 |     4 |
+----+-------+

Si todo esta bien procedemos a eliminar la tabla temp:

drop temporary table temp;
1
  • 1
    Excelente, ahora una pregunta mas, si quiero eliminar esos registros que solo aparecen una sola ves y quedarme con los que se repiten como le hago?
    – Saul
    el 28 sep. 2019 a las 2:52

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.