Delete all but 50 new lines

I have an SQL table with news and Unix timestamps. I would like to keep only 50 latest stories. How can I write an SQL statement to delete any number of old stories?

+3
source share
6 answers

I ended up using two queries since MySQL5 does not yet support LIMIT in subqueries

SELECT unixTime FROM entries ORDER BY unixTime DESC LIMIT 49, 1;
DELETE FROM entries WHERE unixTime < $sqlResult;
+6
source

Blockquote

delete from table where id not in (
    select id from table 
    order by id desc 
    limit 50
)

You select the identifiers of the data that you do not want to delete, and you delete all NOT IN these values ​​...

+8
source

, , , - - , . , - , - . :

select count(*) from table;

do

delete from table order by timestamp limit result - 50;

-

  • MySQL 5
  • MySQL 5 , .
+3

, 50 TRUNCATE TABLE, . 50 .

+2

, , :

SELECT timestampcol FROM table ORDER BY timestampcol DESC LIMIT 49,1;

:

DELETE FROM table WHERE timestampcol < ( SELECT timestampcol FROM table ORDER BY timestampcol DSEC LIMIT 49,1 )

, , , - . , , IN, 50 , , () 50 - , SQL.

-1

Perhaps not the most efficient, but this should work:

DELETE FROM _table_ 
WHERE _date_ NOT IN (SELECT _date_ FROM _table_ ORDER BY _date_ DESC LIMIT 50)
-2
source

Source: https://habr.com/ru/post/1697633/


All Articles