我在我的安卓应用程序中创建了一个 Sqlite 数据库,它看起来像这样:
create table msgs ( id integer primary key autoincrement, msg text not null, session text not null, sender text not null);
我可以像这样得到所有的条目,但我不明白发生了什么。
String[] allColumns = {"msg","session","sender"};
Cursor cursor = database.query(msgs, allColumns, id = insertId, null, null, null, null);
我想做的是,只获取具有不同会话的最新条目,如何在 android 中执行此操作?
编辑:如果这是mysql,我会做"选择MAX(id)作为id2,msg,会话从msgs分组到会话"但是无法接缝使其在SQLite中工作:/
要执行完整的 SQL 查询,您可以使用 rawQuery
:
cursor = database.rawQuery("SELECT MAX(id) AS id2,msg, session FROM msgs GROUP BY session", null);
使用 query
,您必须像这样设置参数:
cursor = database.query("msgs",
new String[] { "MAX(id) AS id2", "msg", "session" },
null, null,
"session",
null, null);
请注意,在聚合查询中使用未聚合的列(msg
)在SQLite版本3.7.11(Android API版本16,Jelly Bean)之前不起作用。
经常检查文档并注意类型!
使用以下方法:
query(
msgs, //String table: OK
allColumns, //String[] columns: OK
id = insertId, //String selection: NOT OK
// ^--- this is a boolean which will render SQL something like
// "SELECT ... WHERE TRUE ..." or "SELECT ... WHERE FALSE ..."
// causing all rows or none to be displayed
null, //String[] selectionArgs: OK
null, //String groupBy: OK
null, //String having: OK
null); //String orderBy: OK
校正:
query(
msgs, //table
allColumns, //columns
"id = ?", //selection
new String[] {String.valueOf(insertId)}, //selectionArgs
null, //groupBy
null, //having
null); //orderBy