我最近开始学习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)
我的想法是每次在同一个用户进入系统时删除userid中的旧记录,就在插入新日志之前。
我已经尝试过这个代码但是有错误:这个版本的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
);
拜托,你能给我一些解决方案吗?谢谢!
答案 0 :(得分:1)
我不是Mysql
的专家,不确定Mysql
中不允许这样做的原因。试试这样的事情
DELETE a
FROM access a
INNER JOIN (SELECT id
FROM access
WHERE userid = 10
ORDER BY id DESC
LIMIT 100) b
ON a.id <> b.id
注意:如评论
中所述,这可能效率不高答案 1 :(得分:0)
尝试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;