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

标签 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;                        
     }

最佳答案

而不是...

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 .

关于android - 在 Android 中使用 SQLite 将 DISTINCT 关键字添加到 query(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17807115/

相关文章:

java - 从一个 Activity 返回到另一个 Activity 时 fragment 可见

android - 无法解析方法 createSpeechRecognizer()

mysql - 需要使此查询在将来针对更大的数据库进行可扩展/优化(删除全表读取)

MySQL:加入很多表

android - Eclipse 无法处理两个 main.xml

java - 重复调用 glBufferData 未能为新缓冲区分配内存

javascript - 将数组作为值传递给 JS

php - 如何向另一台计算机发送和接收 xml

MySQL - 需要使用 WHERE 子句选择 MIN 和 MAX,作为较大查询的一部分

xml - 使用 XML 作为(只读)人类可读的调查问题数据源