我最近开始学习SQL,现在被要求在表上执行简单删除,保留每个用户的最后100条记录.我正在研究最好的方法(更有效的方法)来存档这个,并找到了一些可能的解决方案(
SQL query: Delete all records from the table except latest N?,
Delete all but top n from database table in SQL),但对我来说,选择一个基于效率的方法是错综复杂的.所以我来这里寻求你的帮助.
这是一个名为“access”的表,我们保留用户访问日志.
access:
- id (autoincrement) - primary
- userid (integer 11) - key
- refer (varchar 100)
- date (date/time)
我的想法是每次在同一用户进入系统时从用户ID中删除旧记录,就在插入新日志之前.
我试过这个代码但是有错误:这个版本的MySQL还不支持’LIMIT& IN / ALL / ANY / SOME子查询’
DELETE FROM
access
WHERE
id NOT IN (
SELECT id FROM access WHERE userid = 10 ORDER BY id DESC LIMIT 100
);
拜托,你能给我一些解决方案吗?谢谢!
最佳答案 尝试DELETE JOIN:
delete a from access a left join (
select id
from access
order by id desc limit 1000
) b on a.id = b.id
where b.id is null;
如果要保留给定用户(例如123)的前1000条记录,请执行以下操作:
delete a from access a left join (
select id
from access
where userid = 123
order by id desc limit 1000
) b on a.id = b.id
where b.id is null;
如果要仅为用户123删除行,除了该用户的前1000行:
delete a from access a left join (
select id
from access
where userid = 123
order by id desc limit 1000
) b on a.id = b.id
where b.id is null
and a.userid = 123;