使用MySQL删除数据库表中除最后30行之外的所有行

时间:2013-05-19 06:14:22

标签: php mysql

我有一个简单的问题。如何删除数据库表中除最后30行之外的所有行?例如,请执行以下查询:

DELETE FROM Comments
WHERE got='$user_id'

为了保留最后30行,我还需要做些什么?

这就是Comments表的样子:

enter image description here

3 个答案:

答案 0 :(得分:4)

如果你的版本如果MySQL支持子查询中的限制,那么你可以使用一个子查询来选择30个最近的行。然后,您可以删除除子查询中找到的行之外的所有内容。

DELETE
FROM Comments
WHERE got='$user_id'
  AND got NOT IN
    (SELECT got
     FROM Comments
     ORDER BY TIMESTAMP DESC LIMIT 30)

如果您的MySQL版本不支持子查询中的限制,那么您需要将其拆分为两个单独的查询:

QUERY 1

SELECT got FROM Comments WHERE got='$user_id' ORDER BY TIMESTAMP DESC LIMIT 30

查询1的结果应存储在单个字符串变量中(使用格式1,2,3...)并传递给查询2.(explodeimplode函数可能会派上用场格式化字符串时。)

QUERY 2

DELETE
FROM Comments
WHERE got='$user_id'
  AND got NOT IN ($formatted_result_from_query_1)

答案 1 :(得分:2)

将最后30行存储在临时表中,然后从删除中排除这些行:

CREATE TEMPORARY TABLE tmp AS (SELECT id FROM Comments WHERE got="$user_id" ORDER BY timestamp DESC LIMIT 5);

DELETE FROM Comments
WHERE got="$user_id" AND NOT EXISTS (SELECT id FROM tmp)

答案 2 :(得分:1)

您可以使用LIMIT执行此操作:

DELETE c1
FROM Comments AS c1
LEFT JOIN 
(
   SELECT id 
   FROM comments
   WHERE got = ...
   ORDER BY id DESC
   LIMIT 30
) AS c2  
WHERE c2.id IS NULL;

请在此处查看:

  • SQL Fiddle Demo(我只尝试了5行,并为您的表格提供了简化的架构)