2

我在我的 android 应用程序中创建了一个 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,我会执行“SELECT MAX(id) AS id2,msg, session FROM msgs GROUP BY session”但是不能让它在 SQLite 中工作:/

4

2 回答 2

1

要执行完整的 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)之前,在聚合查询中使用未聚合的列 ( ) 不起作用。

于 2013-11-07T08:06:04.387 回答
0

始终检查文档并注意类型!

您使用以下方法:

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
于 2013-11-07T11:25:47.317 回答