创建指定数量的行后自动修剪?
基本问题,抱歉。基本上,我有一个脚本,每次有人访问该页面时都会创建一个 MySQL 条目。一个日志脚本。然而,我想让它在 100 次访问后自动修剪。
例如在伪代码中:
if amount of rows > 100 { 删除行 1+ 直到行数 == 100 }
所以简而言之,每次在 100 之后添加新行时,都需要自动删除 id 最小的行(我的主键)。
Basic question, sorry. Basically, I have a script that creates a MySQL entry each time someone visits the page. A logging script. However, I want to make it autoprune after, say, 100 visits.
For example in pseudo code:
if amount of rows > 100 {
delete rows 1+ until amount of rows == 100 }
So in a nutshell, each time a new row is added after 100, it needs to automatically remove the row with the smallest id (My primary key).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种可能的选择是使用数据库 TRIGGERS
(http://forge.mysql.com/wiki/Triggers)
这可能有点过分了这种情况下,但每次插入行时都会检查表。
一个例子(我没有测试过!):
创建触发器 prune_MyTable
插入 MyTable 后
对于每一行
开始
声明 num_rows INTEGER;
声明 lower_id INTEGER;
从 MyTable 中选择 COUNT(*) INTO num_rows;
IF 行数 > 100 那么
选择 MIN(id) INTO lower_id
从 MyTable 限制 100;
更新 MyTable 删除 id <最低的_id;
结束如果;
结束$$
Another possible option would be to use database TRIGGERS
(http://forge.mysql.com/wiki/Triggers)
It may be overkill in this scenario but would check the table every time a row is inserted.
An example (which I haven't tested!) :
Create Trigger prune_MyTable
AFTER INSERT ON MyTable
FOR EACH ROW
BEGIN
DECLARE num_rows INTEGER;
DECLARE lowest_id INTEGER;
SELECT COUNT(*) INTO num_rows FROM MyTable;
IF num_rows > 100 THEN
SELECT MIN(id) INTO lowest_id
FROM MyTable LIMIT 100;
UPDATE MyTable DELETE WHERE id < lowest_id;
END IF;
END$$
您很可能必须锁定表才能获取计数,然后删除“正确”数量的旧记录。因此,我宁愿将 SELECT 限制为 100 行,并在表中保留更多记录,即使它们是多余的。您仍然可以删除旧记录,例如,每 x 小时使用 cron 作业一次,或者以每英里 x 的随机概率:
或类似的东西......
(据我所知,DELETE 语句的 ORDER BY 和 LIMIT 子句是最好记住这一点。)
You most likely have to lock the table in order to get the count and then delete the "right" amount of old records. Therefore I'd rather limit the SELECT to 100 rows and keep more records in the table even if they are superfluous. You can still delete old records, e.g. with a cron job once every x hours or with a random probability of x per-mile:
or something like that...
(as far as I know the ORDER BY and LIMIT clause for DELETE statements are MySQL specific. Better keep that in mind.)