0

我正在尝试将 10 个最新条目保留在我的数据库中并删除较旧的条目。我试过DELETE FROM people ORDER BY id DESC LIMIT $excess了,但它只是删除了前 10 个条目。

$query = "SELECT * FROM people";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($count > 10) {
    $excess = $count - 10;
    $query = "DELETE FROM people WHERE id IN(SELECT id FROM people ORDER BY id DESC LIMIT '$excess')";
    mysqli_query($conn, $query);
}
4

4 回答 4

2

像这样的东西?获取子查询中最新的 10 个 id,然后删除所有其他 id。

DELETE FROM people WHERE id NOT IN (SELECT id FROM PEOPLE ORDER BY id DESC LIMIT 10)
于 2013-06-26T17:35:25.893 回答
2

你可以使用这个: -

DELETE FROM `people`
WHERE id NOT IN (
  SELECT id
  FROM (
    SELECT id
    FROM `people`
    ORDER BY id DESC
    LIMIT 10
  ) 
);

此外,您的查询在逻辑上不正确,并且您正在按降序获取记录。即Latest to older,您正在删除最新的记录。改为使用ASC

于 2013-06-26T17:39:07.640 回答
0

您的逻辑无处不在,[you should ORDER BY ASC, not DESC] 如果有 [例如] 10,000 个条目,您的查询将需要很长时间,因为您将有一个IN包含 9,990 个条目的子句来比较所有 10,000 个条目。

选择最近的 10 个,然后删除 NOT in。

DELETE FROM people
  WHERE id NOT IN(
    SELECT id 
    FROM people
    ORDER BY id DESC
    LIMIT 10
  )
于 2013-06-26T17:40:12.327 回答
-1

也许找到第 10 个元素的 ID,然后删除所有较旧的行?

于 2013-06-26T17:33:50.320 回答