保持最后10并删除所有其他行 - sqlite

时间:2014-02-15 09:29:31

标签: android sqlite

我需要执行以下查询。

db.delete(TABLE_SESSIONS, selectQuery, null);

选择查询应该是除最后10个条目之外的那些。

如何实现这一目标?

String selectQuery = "SELECT  * FROM " + TABLE_SESSIONS +" WHERE " +KEY_SESSION_ID+ " IN (SELECT "+KEY_SESSION_ID + " FROM "+TABLE_SESSIONS+" WHERE " +KEY_SESSION_ID+ " ORDER BY Col LIMIT 10)";

任何人都可以改进我的查询吗? (我对查询不满意)

3 个答案:

答案 0 :(得分:3)

尝试以下查询。

String selectQuery = "SELECT  * FROM " + TABLE_SESSIONS +" WHERE " +KEY_SESSION_ID+ " IN (SELECT "+KEY_SESSION_ID + " FROM "+TABLE_SESSIONS+" WHERE " +KEY_SESSION_ID+ " ORDER BY Col DESC LIMIT 10)";  

答案 1 :(得分:3)

SQLiteDatabase delete()接受WHERE表达式而不是SELECT语句。

如果您的选择返回了您要保留的行:

String selectQuery = "SELECT  * FROM " + TABLE_SESSIONS +" WHERE " +KEY_SESSION_ID+ " IN (SELECT "+KEY_SESSION_ID + " FROM "+TABLE_SESSIONS+" WHERE " +KEY_SESSION_ID+ " ORDER BY Col LIMIT 10)"

...您可以使用NOT IN进行删除,如下所示:

db.delete(TABLE_SESSIONS,
    "ROWID NOT IN (SELECT ROWID FROM " + TABLE_SESSIONS + " ORDER BY Col LIMIT 10)",
    null);

ROWID是表格INTEGER PRIMARY KEY的别名;您的子选择中的WHERE条件不是必需的,因为任何非零ID都会被选中。

答案 2 :(得分:2)

SELECT * FROM TABLE_SESSIONS WHERE YOUR_SORT_FIELD NOT IN (select TOP 10 YOUR_SORT_FIELD from TABLE_SESSIONS order by YOUR_SORT_FIELD DESC)

如果您需要最后10个或最新10个

,则可以更改

DESCASC

YOUR_SORT_FIELD是标识最新数据的字段