Eliminar todo excepto n superior de la tabla de base de datos en SQL


¿Cuál es la mejor manera de eliminar todas las filas de una tabla en sql sino mantener n número de filas en la parte superior?

 71
sql
Author: Riri, 2008-09-05

9 answers

DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table)

Editar:

Chris trae un buen éxito de rendimiento ya que la consulta TOP 10 se ejecutaría para cada fila. Si esto es una cosa de una sola vez, entonces puede que no sea tan importante, pero si es una cosa común, entonces lo miré más de cerca.

 64
Author: Cory Foy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-07 08:28:05

Seleccionaría ID columna(s) el conjunto de filas que desea mantener en una tabla temporal o variable de tabla. A continuación, elimine todas las filas que no existen en la tabla temp. La sintaxis mencionada por otro usuario:

DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table)

Tiene un problema potencial. La consulta" SELECT TOP 10 " se ejecutará para cada fila de la tabla, lo que podría ser un gran éxito de rendimiento. Desea evitar hacer la misma consulta una y otra vez.

Esta sintaxis debería funcionar, basada en lo que listó como su sentencia SQL original:

create table #nuke(NukeID int)

insert into #nuke(Nuke) select top 1000 id from article

delete article where not exists (select 1 from nuke where Nukeid = id)

drop table #nuke
 30
Author: Chris Miller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-30 10:06:50

Referencia futura para aquellos de uso que no usan MS SQL.

En PostgreSQL use ORDER BY y LIMIT en lugar de TOP.

DELETE FROM table
WHERE id NOT IN (SELECT id FROM table ORDER BY id LIMIT n);

MySQL well bueno...

Error This Esta versión de MySQL aún no soporta ' LIMIT & EN/ALL/ANY / SOME subconsulta '

Todavía no, supongo.

 8
Author: Simurr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-17 10:09:09

Creo que usar una tabla virtual sería mucho mejor que una tabla IN-clause o temp.

DELETE 
    Product
FROM
    Product
    LEFT OUTER JOIN
    (
        SELECT TOP 10
            Product.id
        FROM
            Product
    ) TopProducts ON Product.id = TopProducts.id
WHERE
    TopProducts.id IS NULL
 4
Author: Tim Wilson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-05 05:18:43

No conozco otros sabores pero MySQL DELETE permite el LÍMITE.

Si pudiera ordenar las cosas de manera que las n filas que desea mantener estén en la parte inferior, entonces podría eliminar DEL LÍMITE DE tabla tablecount-n.

Editar

Oooo. Creo que me gusta la respuesta de Cory Foy mejor, asumiendo que funciona en tu caso. Mi manera se siente un poco torpe en comparación.

 2
Author: Mark Biek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:53

Esto realmente va a ser específico del lenguaje, pero es probable que use algo como lo siguiente para SQL server.

declare @n int
SET @n = SELECT Count(*) FROM dTABLE;
DELETE TOP (@n - 10 ) FROM dTable

Si no le importa el número exacto de filas, siempre hay

DELETE TOP 90 PERCENT FROM dTABLE;
 1
Author: Noah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-03 22:15:44

Lo resolvería usando la técnica de abajo. El ejemplo espera una tabla article con un id en cada fila.

Delete article where id not in (select top 1000 id from article)

Editar: Demasiado lento para responder a mi propia pregunta ...

 0
Author: Riri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-05 17:49:10

Refactorizado?

Delete a From Table a Inner Join (
    Select Top (Select Count(tableID) From Table) - 10) 
        From Table Order By tableID Desc
) b On b.tableID = A.tableID

editar: probó ambos en el analizador de consultas, la respuesta actual es rápida (maldito orden por...)

 0
Author: Shawn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-05 18:35:35

La mejor manera sería insertar las filas que desea en otra tabla, soltar la tabla original y luego cambiar el nombre de la nueva tabla para que tenga el mismo nombre que la tabla anterior

 0
Author: SQLMenace,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-05 18:37:40