我创建了一个具有“最近历史记录”的Android应用程序。
我希望将此表的大小限制为最多50行(根据它们的插入日期)。
我看到了一些讨论限制删除行数的线程,但我不确定这个功能是否在Android的SQLite中启用。
有人可以帮忙吗?
谢谢
我看到了一些讨论限制删除行数的线程,但我不确定这个功能是否在Android的SQLite中启用。
有人可以帮忙吗?
谢谢
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 ...
我不确定在对大表使用IN
和NOT IN
时性能的差异,但对于你的问题来说没有区别。
BEFORE
、AFTER
或 INSTEAD OF
吗?https://www.sqlite.org/lang_createtrigger.html - IgorGanapolsky我认为SQL无法管理您的表中的行数,因此您必须自己进行管理。您可以在数据插入后执行查询以减少数据量 - 像这样的查询应该有效。
DELETE FROM table where _id NOT IN (SELECT _id from table ORDER BY insertion_date DESC LIMIT 50)
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);
}
}
VACUUM
命令,如此处所建议的。 - JJD