在表格中保留最新的n个条目

时间:2012-04-14 22:26:58

标签: java android sql sqlite

我有一个sqlite数据库(在android上),我想存储一些数据的最新N个条目。

表的主键是日期字段。基本上每当我在达到阈值后插入一些行时,我想从表中删除最旧的条目。

有没有特别聪明/好的方法来做到这一点?请注意,我总是在每次插入后检查不变量(nr rows< = THRESHOLD),因此我们不必处理任何事情,只需删除最旧的条目。

我打算做的基本上是:

  1. 插入数据
  2. 如果表< = THRESHOLD:goto 4
  3. 的count(*)
  4. DELETE FROM table WHERE date ==(从日期表中按日期选择日期ASC LIMIT 1);
  5. DONE
  6. 注意我正在使用ORMlite,但由于没有涉及用户数据,我只能使用原始SQL,所以应该没有问题。

3 个答案:

答案 0 :(得分:2)

DELETE FROM table WHERE date = (SELECT MAX(date) from table LIMIT 1);

答案 1 :(得分:1)

添加新行时,您可以使用触发器删除最旧的行,并且行数超过阈值。

行数可以保存在单独的记帐表中,以避免每次插入时出现COUNT。

这是一个完整的例子:

create table bookkeepings (bk_name text primary key, bk_value integer not null);

insert or replace into bookkeepings values ('Max Results', 50);
insert or replace into bookkeepings values ('Qty Results', 0);

create table results
  (r_timestamp text primary key default (datetime(current_timestamp)),
   result text);

create trigger results_limit_trigger before insert on results"
  for each row"
  when (select bk_value from bookkeepings where bk_name = 'Qty Results')
    >= (select bk_value from bookkeepings where bk_name = 'Max Results')
  begin
    delete from results
      where r_timestamp = (select r_timestamp from results order by r_timestamp limit 1);
  end;

create trigger results_count_insert_trigger after insert on results
  for each row
  begin
    update bookkeepings set bk_value = bk_value + 1 where bk_name = 'Qty Results';
  end;

create trigger results_count_delete_trigger after delete on results
  for each row
  begin
    update bookkeepings set bk_value = bk_value - 1 where bk_name = 'Qty Results';
  end;

答案 2 :(得分:1)

这个怎么样?

-- keep the last N records by expiration date
declare @expDate datetime

set @expDate = (select top 100 max(dt) from table order by dt asc);
delete from table where dt > @expDate