0

我有这样的事情:

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

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

请帮忙,我需要什么以及如何更新我的代码,以及什么会更好地使用窗口函数OVER()的限制+偏移量 或需要另一个?

4

2 回答 2

1

加入获取最近 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;
于 2018-06-14T16:38:20.187 回答
0

完全不用怎么delete办?编写查询以保存所需的记录。然后截断表并将它们重新插入:

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;
于 2018-06-14T16:17:07.220 回答