删除行:没有单个成员拥有超过 x 条记录
我有一个如下结构的表:
CREAT TABLE `member_logins` (
`id` bigint(10) unsigned not null auto_increment,
`member_id` mediumint(8) unsigned not null,
`date_created` datetime not null,
PRIMARY KEY(`id`)
) ENGINE=InnoDB;
我只想为每个成员保留 50 次登录记录。所以我正在寻找一种方法来删除每个成员的行,任何超过最近 50 行的行。
编辑:我应该提到...这将是一个每晚的 cron 作业。不是需要实时完成的事情。
I have a table structured like this:
CREAT TABLE `member_logins` (
`id` bigint(10) unsigned not null auto_increment,
`member_id` mediumint(8) unsigned not null,
`date_created` datetime not null,
PRIMARY KEY(`id`)
) ENGINE=InnoDB;
I only want to keep 50 logins recorded for each member. So I'm looking for a way to DELETE rows on a per member basis, any rows past the most recent 50.
Edit: I should have mentioned... This would be a nightly cron job. Not something that needs to be done in real time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
修复了查询。对样本数据进行了测试,它对我有用。
我加载用于测试的示例数据
而不是 50,我在查询中使用前 2 行进行测试。
所以我的查询应该删除排名 > 的所有行每个 member_id 组中的 2 个行按 date_created desc 排序。
运行删除查询后的输出:
您可以看到 ID 为 1 和 5 的行已被删除。这些是排名 > 的行。每个member_id组中有2个
Fixed the query. Tested on sample data and it works for me.
Sample Data i loaded for testing
Instead of 50, i have in the query top 2 rows for testing.
So my query should delete all rows which are having rank > 2 in each member_id group where in rows ordered by date_created desc.
Output after running the delete query:
You can see the rows with ID 1 and 5 got deleted. These are the rows having rank > 2 in each member_id group
不 - 不是解决问题的正确方法 - 批处理作业很难管理和测试,并且对于大多数面向互联网的站点来说,没有每日停机时间。最好分散负载,并且仅在需要时运行代码,即当用户登录时......
使用member_id 上的索引会更有效
No - not the right way to fix the problem - batch jobs are difficult to manage and test, and for most internet facing sites there is no daily downtime. It's much better to spread the load, and only run the code when you need to, i.e. when a user logs in....
Which will be a lot more efficient with an index on member_id
PsuedoCode - 这很可能会进入存储过程或程序逻辑:
现在插入新的成员登录记录。
PsuedoCode - Most likely this would go in stored proc or program logic:
Now insert the new member login record.
子查询
可以替换为
member
表中的简单 SELECT:The subquery
can be replaced by a simple SELECT from your
member
table: