删除某些日期较旧的记录,但如果删除所有记录,请保留最近20条记录

时间:2018-06-14 16:12:17

标签: mysql sql mysql-5.0

我有这样的事情:

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

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

请帮助,我需要更新我的代码的内容和方式,以及更好的使用窗口函数的限制+偏移 OVER()或需要另一个?

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;
相关问题