Mysql

MySql:刪除所有大於按日期時間排序的 n 個條目的行

  • June 30, 2021

有人可以幫助我使用 MySql 查詢刪除所有大於按日期排序的 n 個條目的行嗎?

也就是說,我有 1200 行帶有時間戳列的數據。我需要按日期排序並僅保留前 200 行。

如果我只有 199 行數據,那麼我需要將它們全部保留。

這將保留前 200 行(可能還有更多,具有相同的時間戳):

DELETE t
FROM 
   tableX AS t
 JOIN
   ( SELECT timestampColumn AS ts
     FROM tableX
     ORDER BY ts ASC
     LIMIT 1 OFFSET 199
   ) tlimit
   ON t.timestampColumn > tlimit.ts

附加問題:為每個使用者保留前 200 行(按uid列):

DELETE tt
FROM 
     ( SELECT DISTINCT uid             --- these 3 lines can be replaced
       FROM tableX                     --- with:   UserTable AS du
     ) AS du                           --- a table that you probably have
 JOIN
     tableX AS tt
   ON  tt.uid = du.uid
   AND tt.timestampColumn >
       ( SELECT timestampColumn AS ts
         FROM tableX
         WHERE uid = du.uid 
         ORDER BY ts ASC
         LIMIT 1 OFFSET 199
       )

A(uid, timestampColumn)對一張大桌子很有用。

引用自:https://dba.stackexchange.com/questions/11258