2

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

DELETE FROM Comments
WHERE got='$user_id'

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

这是Comments表格的样子:

在此处输入图像描述

4

3 回答 3

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 版本不支持 sub-queries 中的限制,那么您需要将其拆分为两个单独的查询:

查询 1

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

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

查询 2

DELETE
FROM Comments
WHERE got='$user_id'
  AND got NOT IN ($formatted_result_from_query_1)
于 2013-05-19T06:26:21.257 回答
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)
于 2013-05-19T06:26:05.863 回答
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 行,为您的表提供了简化的架构)
于 2013-05-19T06:19:43.820 回答