在MySQL中删除最旧的10行

时间:2012-08-29 15:50:43

标签: mysql

我需要一个MySQL语句来从我的表中删除最旧的10个条目,但是我能得到的最接近的是:

   DECLARE ID INT;
   SET ID = (SELECT CallbackID FROM callbacks ORDER BY CallbackID LIMIT 1 OFFSET 9);

   DELETE FROM callbacks WHERE callbackID <= ID;

如果总是有至少10个条目,那就没问题,但是当有少量条目时,ID没有设置,因此删除语句失败。

有什么想法吗? 感谢

编辑: 试过这个:

   DECLARE ID INT;
   SET ID = (SELECT CallbackID FROM callbacks ORDER BY CallbackID LIMIT 1 OFFSET 9);

   if ID IS NOT NULL THEN

   DELETE FROM callbacks WHERE callbackID <= ID;
   END IF;

4 个答案:

答案 0 :(得分:1)

DELETE FROM callbacks 
WHERE callbackID in (
    SELECT CallbackID 
    FROM callbacks 
    ORDER BY CallbackID LIMIT 10
)

答案 1 :(得分:1)

怎么样:

DELETE FROM callbacks ORDER BY CallbackID LIMIT 10;

Yeah, it works :)

答案 2 :(得分:1)

DELETE FROM callbacks ORDER BY callbackID DESC LIMIT 10

答案 3 :(得分:1)

SET之后,您只需要一个if语句来检查ID是否已设置,如果是,则执行查询,否则执行其他操作或不执行任何操作。