【问题标题】:How to get a cursor with distinct values only?如何获得仅具有不同值的游标?
【发布时间】:2012-01-09 11:05:03
【问题描述】:

我只想返回具有不同列值的游标。 “组”列有更多项目,但只有 2 个值:1,2,1,1,1,2,2,2,1

String[] FROM = {Groups,_ID};

public Cursor getGroups(){
//......
return db.query(TABLE_NAME,FROM,null,null,null,null,null);
}

将返回一个包含 {1,2,1,1,1,2,2,2,1} 的游标,但我想只包含 {1,2}。

【问题讨论】:

    标签: android sqlite android-cursor distinct-values


    【解决方案1】:

    你可以有这样的sql查询,

    public Cursor usingDistinct(String column_name) {
            return db.rawQuery("select DISTINCT "+column_name+" from "+TBL_NAME, null);
        }
    

    【讨论】:

    • 错误是因为你确实在Cursor cursor = getGroups();之后调用了cursor.moveToFirst();
    • 现在我想从游标中提取值。我试过了:String gr1 = cursor.getString(0); String gr2 = cursor.getString(1);` 但我得到错误:CursorIndexOutOfBoundsException: Index -1 requested, with a size of 2。然后我将其更改为:Cursor cursor = db.rawQuery("select DISTINCT "+column_name+" from "+TABLE_NAME,null); if(cursor != null){ cursor.moveToFirst(); } return cursor;,现在,我可以访问第一个值,getString(0)。当我尝试 getString(1) 时,我得到 NULL。知道如何从光标中提取两个值吗?感谢现在提供的解决方案。
    • 我发现,我不应该调用 cursor.getString(1) 因为游标只有 1 列和更多行。相反,我应该这样做:while(cursor.moveToNext()){ ....cursor.getString(0); ....... } 光标具有 wright 内容,所有不同的值。
    • 如果我想要不同列的整行怎么办?
    【解决方案2】:

    您可以在进行这样的查询时使用 distinct 参数:

    public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
    

    请关注此doc 以获得更多信息。

    【讨论】:

    • 正是我想要的:)
    【解决方案3】:

    您可以使用下面的示例查询,因为您必须为不同的列提供名称

    Cursor cursor = db.query(true, YOUR_TABLE_NAME, new String[] { COLUMN_NAME_1 ,COLUMN_NAME_2, COLUMN_NAME_3 }, null, null, COLUMN_NAME_2, null, null, null);
    

    COLUMN_NAME_2 - 不同列的名称。

    记得添加 GROUP BY 列名

    【讨论】:

      【解决方案4】:

      在 distinct 参数中使用布尔 true,例如:

      public Cursor query (**true**, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);
      

      【讨论】:

        猜你喜欢
        • 2013-02-14
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        • 2014-11-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多