限制房间数据库中的行数

Limit the number of rows in a room database

如何通过删除行中最旧的项目并插入最新的项目来限制 Android 房间数据库中的行数?

我猜这是向数据库添加项目时的标准查询?

EDIT:我想限制数据库 table 的最大行数为 20。如果达到该限制,我们将删除最旧的项目并通过将当前行数保持为 20 来插入新行。

按照以下步骤操作:

1> 获取 table

的行数
your_count = SELECT count( * ) FROM table_name;

2> 如果计数 >(大于)20 则获取最旧的记录

SELECT *
  FROM table_name
 ORDER BY entry_Date ASC
 LIMIT 1;

3> 现在删除这些选定的记录

4> 插入新数据

注意:如果要插入多个条目而不是将其放入循环

我认为您可以将数据插入 table,然后删除除最后 20 行以外的所有行(限制)

要删除您可以使用以下查询

DELETE FROM tableName where id NOT IN (SELECT id from tableName ORDER BY id DESC LIMIT 20)

在本例中,id是设置为自增的主键。如果按日期

存储它们,也可以使用日期作为键

假设:

你的table是

    create table example_table (
      ts timestamp,
      uid number(19),
      some_other_field varchar(64)
    );

而且您不想手动关心 运行 一些查询。

使用数据库触发器:

    create trigger
      if not exists -- I don't actually know if you DB will support this line.
                    -- Might want to remove it if it's not.
    example_table_limiter
    on example_table
    after insert
    begin
      delete
      from example_table
      where ts in (
        select ts
        from example_table
        order by ts 
        limit -1 -- we don't want to limit how many rows we want to delete
        offset 25 -- but we want to offset query result so it leaves 25 rows in table
      );
    end;

“无限制偏移”语法的灵感来自 this answer

要在 java 中启用触发器:

简单 Android,您可以在其中覆盖 SQLiteOpenHelper:

    public class DataBaseSchemaHelper extends SQLiteOpenHelper {
      @Override
      public void onCreate(SQLiteDatabase db) {     
        db.execSQL(<trigger string from above>);
      }
    }

Android房间版本:

     public class MyDatabase extends RoomDatabase {
       @Override
       public void init(DatabaseConfiguration _config) {
         super.init(_config);
         getOpenHelper().getWritableDatabase().execSQL(<trigger string from above>);
       }
     }

这是示例解决方案:

查询是:

@Query("SELECT * FROM user LIMIT :limit OFFSET :offset")
    User[] loadAllUsersByPage(int limit,int offset);

这里会给出一个基于limit和offset的用户列表。

如果 loadAllUsersByPage(2,0) 它将 return 来自 table 的前 2 行。

如果 loadAllUsersByPage(2,1) 它将 return 来自 table 的第 2 和第 3 行。

但如果 loadAllUsersByPage(-1,10) 则它将提供 table 的前 10 行。

您可以通过这样做来限制 columns/rows:此查询将 return 新数据并在达到限制时删除旧数据。

解释:

  1. 第一个查询是select所有数据按降序排列
  2. 第二个查询是从 columns/rows id > 20
  3. 中删除数据

如果您希望 table 只有 20 行,则将 OFFSET 设置为 20,LIMIT 表示如何一次插入和删除多行。

在我的示例中,当用户输入 1 个新数据时,我删除了 1 行(oldest/last 行)


  @Query("SELECT * FROM my_table ORDER BY timeStamp DESC")
  fun getAllData(): List<MyEntityClass>

  @Query("DELETE FROM my_table WHERE id IN (SELECT id FROM my_table ORDER BY timeStamp DESC LIMIT 1 OFFSET 20)")
  fun removeOldData()