我需要执行以下查询。
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)";
任何人都可以改进我的查询吗? (我对查询不满意)
答案 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)
DESC
和ASC
和YOUR_SORT_FIELD
是标识最新数据的字段