如何在Android SQLite表中限制行数

23
我创建了一个具有“最近历史记录”的Android应用程序。 我希望将此表的大小限制为最多50行(根据它们的插入日期)。
我看到了一些讨论限制删除行数的线程,但我不确定这个功能是否在Android的SQLite中启用。
有人可以帮忙吗?
谢谢

还要考虑包含SQL VACUUM命令,如此处所建议的。 - JJD
3个回答

22
创建触发器。
CREATE TRIGGER delete_till_50 INSERT ON _table WHEN (select count(*) from _table)>50 
BEGIN
    DELETE FROM _table WHERE _table._id IN  (SELECT _table._id FROM _table ORDER BY _table._id limit (select count(*) -50 from _table ));
END;

编辑:

你可以像Mojo Risin所写的那样将
DELETE FROM ... WHERE ... IN ...
改为
DELETE FROM ... WHERE ... NOT IN ...
我不确定在对大表使用INNOT IN时性能的差异,但对于你的问题来说没有区别。


1
你需要像这里描述的那样使用 BEFOREAFTERINSTEAD OF 吗?https://www.sqlite.org/lang_createtrigger.html - IgorGanapolsky

16

我认为SQL无法管理您的表中的行数,因此您必须自己进行管理。您可以在数据插入后执行查询以减少数据量 - 像这样的查询应该有效。

DELETE FROM table where _id NOT IN (SELECT _id from table ORDER BY insertion_date DESC LIMIT 50)

1
插入日期长什么样?SQLite 只能接受字符串,所以你不能像那样排序日期... - IgorGanapolsky
我们可以将日期时间转换为毫秒,然后可以使用它们。 - Ankur Chaudhary

3
请查看SearchRecentSuggestions的源代码,您可以从中获得一个示例。它有一个方法可以截断历史记录到给定数量的条目,使用LIMIT -1 OFFSET <maxEntries>。您必须首先按插入的相反顺序对条目进行排序,然后跳过前面的maxEntries
如果您在每次插入时自动调用此方法,则只需要LIMIT 1,因为最多可以有maxEntries + 1个条目。
/**
 * Reduces the length of the history table, to prevent it from growing too large.
 *
 * @param cr Convenience copy of the content resolver.
 * @param maxEntries Max entries to leave in the table. 0 means remove all entries.
 */
protected void truncateHistory(ContentResolver cr, int maxEntries) {
    if (maxEntries < 0) {
        throw new IllegalArgumentException();
    }

    try {
        // null means "delete all".  otherwise "delete but leave n newest"
        String selection = null;
        if (maxEntries > 0) {
            selection = "_id IN " +
                    "(SELECT _id FROM suggestions" +
                    " ORDER BY " + SuggestionColumns.DATE + " DESC" +
                    " LIMIT -1 OFFSET " + String.valueOf(maxEntries) + ")";
        }
        cr.delete(mSuggestionsUri, selection, null);
    } catch (RuntimeException e) {
        Log.e(LOG_TAG, "truncateHistory", e);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接