1. 程式人生 > >mysql刪除舊資料,保留最新的m條記錄

mysql刪除舊資料,保留最新的m條記錄

sql如下:

select   *  from  area_table ORDER BY id limit 1670,1  -- 結果id=1671 1條記錄

select   *  from  area_table ORDER BY id limit 10 -- 結果id = 1...10 前10條記錄

delete from area_table where id <
(select   id  from  area_table ORDER BY id desc limit 1670,1)
-- 錯誤
--  You can't specify target table 'area_table' for update in FROM clause

delete from area_table where id  not in (
select   id   from  area_table ORDER BY id desc limit 1000,1
) -- 錯誤
-- [Err] 1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

delete from area_table a ,(select   id   from  area_table ORDER BY id desc limit 1000,1) b
where a.id<b.id -- 錯誤

delete a from area_table a join (select   id   from  area_table ORDER BY id desc limit 901,1) b
on a.id<b.id  -- 正常

delete a from area_table a ,(select   id   from  area_table ORDER BY id desc limit 2000,1) b
where a.id<b.id -- 正常,沒有2000條資料時不刪除

delete a from area_table a ,(select  DISTINCT id   from  area_table ORDER BY id desc limit 900,1) b
where a.id<b.id -- 正常

版本:5.7.14