创建指定数量的行后自动修剪?

发布于 2024-08-31 19:51:09 字数 224 浏览 4 评论 0原文

基本问题,抱歉。基本上,我有一个脚本,每次有人访问该页面时都会创建一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温暖的光 2024-09-07 19:51:09

另一种可能的选择是使用数据库 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$$

爱的故事 2024-09-07 19:51:09

您很可能必须锁定表才能获取计数,然后删除“正确”数量的旧记录。因此,我宁愿将 SELECT 限制为 100 行,并在表中保留更多记录,即使它们是多余的。您仍然可以删除旧记录,例如,每 x 小时使用 cron 作业一次,或者以每英里 x 的随机概率:

if ( 10 > rand(0, 8000) ) {
  LOCK TABLES foo
  SELECT COUNT(*) as cnt FROM foo
  if ( $cnt > 100 ) {
    $cnt -= 100;
    DELETE FROM foo ORDER BY id DESC LIMIT $cnt
  }
  UNLOCK TABLES
}

或类似的东西......

(据我所知,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:

if ( 10 > rand(0, 8000) ) {
  LOCK TABLES foo
  SELECT COUNT(*) as cnt FROM foo
  if ( $cnt > 100 ) {
    $cnt -= 100;
    DELETE FROM foo ORDER BY id DESC LIMIT $cnt
  }
  UNLOCK TABLES
}

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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文