删除前几天的记录,但如果全部删除,保留最后 20 条记录

Delete records that older some days, but if it delete all, keep last 20 records

我有这样的东西:

DELETE FROM `history` WHERE `date_field` <= now() - INTERVAL 10 DAY

但如果所有记录都超过 10 天 - 此查询将全部删除!我想保留最近 20 条记录,即使它们太旧了!

请帮忙,我需要什么以及如何更新我的代码,什么会更好地使用窗口函数的 limit+offset OVER() 还是需要另一个?

完全不使用 delete 怎么样?写一个查询来保存你想要的记录。然后截断 table 并将它们重新插入:

create temporary table tokeep as
    select h.*
    from history h
    where `date_field` > now() - INTERVAL 10 DAY
    union
    select h.*
    from history h
    order by date_field desc
    limit 20;

truncate table history;

insert into history  -- the only situation where I don't list the columns
    select *
    from tokeep;

加入一个获取最近 20 天并排除它们的子查询。

DELETE h1 
FROM history AS h1
LEFT JOIN (
    SELECT id
    FROM history
    ORDER BY date_field DESC
    LIMIT 20
) AS h2 ON h1.id = h2.id
WHERE date_field < now() - INTERVAL 10 DAY
AND h2.id IS NULL;