Mysql删除除100个新行以外的所有行

时间:2015-11-24 10:31:09

标签: php mysql

你好我需要清空所有表,除了我已经测试的x新行

How to delete all rows from a table except newest 10 rows

SQL Delete all rows except for last 100

但不行,我的mysql版本不支持限制" IN" (实际版本Ver 14.14 Distrib 5.5.46)

我的桌子就像那样

ID (int)
DATE (timestamp)

我可以在没有循环的情况下清空感谢

3 个答案:

答案 0 :(得分:3)

试试这个

<?php
$mysqli=new mysqli("localhost", "root", "", "db");
$result=$mysqli->query("select id from tabl order by id desc" );
$res=$result->fetch_array();
echo $res[0];
$id=$res[0]-100;
$mysqli->query("delete from table where id < $id");
?>

答案 1 :(得分:2)

您可以使用一个使用变量的SQL DELETE语句来执行此操作:

DELETE mytable
FROM mytable 
INNER JOIN (
  SELECT ID, @rn := @rn + 1 AS rn
  FROM mytable
  CROSS JOIN (SELECT @rn := 0) AS var
  ORDER BY DATE DESC
) AS t ON mytable.ID = t.ID
AND t.rn > 100

派生的tas牌t用于为ID的每个mytable分配一个行号。编号使用ORDER BY DATE DESC,因此100个最近的记录将在[1-100]中具有rnDELETE删除mytable中的任何一行,但[1-100]中rn除外。

Demo here(Demo最近记录了10条而不是100条)

答案 2 :(得分:1)

您可以依次使用多个SQL语句来完成此操作。

您可以通过获取要删除的第一个ID来执行此操作,然后删除ID

更新的所有行
// Create the memory table for storing the IDs
create table mem(
   first100 integer
);

// Insert to the memory table the list of 100 last ids
insert into mem(first100) select id from table order by id desc limit 100;

// Insert to Mysql variable @a, the id of the first id  to delete
set @a=select fist100 from mem order by id limit 1;

// Delete all the id's after the one you want to delete
delete from table where id>=@a

<强>更新 我发布了这个答案,因为你错误地认为错误信息是:This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME

无论如何,我保留它,也许这种方法对其他人有帮助。