使用Android中的SQLite将DISTINCT关键字添加到query()

时间:2013-07-23 10:04:34

标签: android sql database sqlite

在进行更复杂的SQL查询时,SQLite中query()和rawQuery()之间的区别。

例如

我想使用SQL关键字DISTINCT,所以我没有从数据库中返回任何重复项。 我理解如何使用rawQuery()方法,这样你就可以在方法中放入一个实际的SQL查询语句。通过这种方式,我可以使用rawQuery制作标准的SQL语句。使用rawQuery()

时,很容易将DISTINCT关键字添加到任何SQL语句中

但是,当使用此代码中显示的query()方法时,我不能只使用常规SQL语句。在这种情况下,如何使用DISTINCT关键字作为查询的一部分进行查询?或具有相同功能的东西?

            // get info from country table
            public String[] getCountries(int numberOfRows) {

                     String[] columns = new String[]{COUNTRY_NAME};
                     String[] countries = new String[numberOfRows];

                     int counter = 0;

                Cursor cursor = sqLiteDatabase.query(COUNTRY_TABLE, columns, 
                            null, null, null, null, null);

                     if (cursor != null){

                     while(cursor.moveToNext()){
         countries[counter++] = cursor.getString(cursor.getColumnIndex(COUNTRY_NAME));                                   
                    }

            }
                return countries;                        
     }

4 个答案:

答案 0 :(得分:7)

而不是......

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

...您正在使用的方法,只需使用...

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

...重载并将distinct设置为true

Android文档似乎有点难以直接链接,但描述两者的文档页面是here

答案 1 :(得分:2)

你可以使用它,

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

这里第一个参数用于设置DISTINCT值,即如果设置为true,它将返回不同的列值。

和第六个参数表示您想要GROUP BY的列名。

答案 2 :(得分:1)

您应该使用另一个QUERY函数,并将第一个DISTINCT布尔参数设置为TRUE

public Cursor query (boolean distinct, String table,...)

答案 3 :(得分:0)

这是我在我的应用程序中使用的函数,用于从组表中获取distist名称,希望您能够了解它,看看它。如果列包含相同的名称,将仅提取不同的值

public ArrayList<String> getGroupNames() {

    ArrayList<String> groups = new ArrayList<>();

    SQLiteDatabase db = this.getReadableDatabase();

    String[] projection = {COLUMN_GROUP_NAME};

    //select distinct values for group name from group table

    Cursor cursor = db.query(true,GROUPS_TABLE_NAME, projection, null, null, COLUMN_GROUP_NAME, null, null,null);

    if (cursor.moveToFirst()) {

        do {
            String group=cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_GROUP_NAME));
            groups.add(group);
            Log.d("group",group+"gp");

        }while (cursor.moveToNext());

    }
    return groups;

}