我正在尝试将最近的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);
}
答案 0 :(得分:2)
这样的东西?获取子查询中的十个最新ID,然后删除所有其他ID。
DELETE FROM people WHERE id NOT IN (SELECT id FROM PEOPLE ORDER BY id DESC LIMIT 10)
答案 1 :(得分: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
。
答案 2 :(得分:0)
你的逻辑到处都是,[你应该ORDER BY ASC
,而不是DESC
],如果有[例如] 10,000个条目,你的查询会花费很长时间,因为你有一个{{ 1}}子句,包含9,990个条目,用于比较所有10,000到。
选择最近的10个,并删除不在的位置。
IN
答案 3 :(得分:-1)
也许找到第10个元素的ID,然后删除所有较旧的行?