How to get a cursor with distinct values only?

2019-01-28 03:41发布

I want to return a cursor only with distinct values of a column. The column 'Groups' has more items but with only 2 values: 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);
}

will return a cursor containing {1,2,1,1,1,2,2,2,1} but I would like to contain just {1,2}.

3条回答
Emotional °昔
2楼-- · 2019-01-28 04:35

you can use distinct argument while making query like this:

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

Follow this doc for more clearity.

查看更多
来,给爷笑一个
3楼-- · 2019-01-28 04:35

You can use below example query, as you have to give column name for distinct

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 - name of the column for distinct.

remember to add GROUP BY column names

查看更多
仙女界的扛把子
4楼-- · 2019-01-28 04:38

You can have an sql query like this,

public Cursor usingDistinct(String column_name) {
        return db.rawQuery("select DISTINCT "+column_name+" from "+TBL_NAME, null);
    }
查看更多
登录 后发表回答