2013-03-02 113 views
0

我的光標返回記錄兩次,即使我設置了不同的爲true:顯示不同記錄的SQLite的Android

回報myDataBase.query(真,DB_TABLE,新的String [] { 「ROWID作爲_id」,KEY_CONDITIONS },builder.toString(),症狀,null,null,null,null);

僅供參考,

public Cursor getData(String[] symptoms) { 
    String where = KEY_SYMPTOMS + "= ?"; 
    String orStr = " OR "; 

    StringBuilder builder = new StringBuilder(where); 
    for(int i = 1; i < symptoms.length; i++) 
     builder.append(orStr).append(where); 

    return myDataBase.query(true, DB_TABLE, new String[] 
      {"rowid as _id", KEY_CONDITIONS}, builder.toString(), symptoms, null, null, null, null); 

} 

或者我試圖改變rawQuery

return myDataBase.rawQuery("SELECT DISTINCT " + KEY_CONDITIONS + " FROM " 
    + DB_TABLE + " " + builder.toString() + symptoms.toString(), null); 

我logcat的說:

03-02 22:57:02.634: E/AndroidRuntime(333): FATAL EXCEPTION: main 
    03-02 22:57:02.634: E/AndroidRuntime(333): android.database.sqlite.SQLiteException: near "=": syntax error: , while compiling: SELECT DISTINCT conditions FROM tblSymptoms symptoms= ? OR symptoms= ?[Ljava.lang.String;@405550f8 

請幫我鑑定一下似乎缺少在這裏。任何幫助是真正的讚賞。

enter image description here

回答

7

解決方案
你想DISTINCT條件,但Android的需要_id列這是一個問題,因爲你不能混搭: SELECT _id, DISTINCT condition... 。但是你可以使用GROUP BY條款改爲:

return myDataBase.query(DB_TABLE, new String[] {"rowid as _id", KEY_CONDITIONS}, 
     builder.toString(), symptoms, KEY_CONDITIONS, null, null); 

說明
這個查詢:

return myDataBase.rawQuery("SELECT DISTINCT " + KEY_CONDITIONS + " FROM " 
    + DB_TABLE + " " + builder.toString() + symptoms.toString(), null); 

失敗,因爲你正在傳遞String[] symptoms在錯誤的參數,請嘗試:

return myDataBase.rawQuery("SELECT DISTINCT " + KEY_CONDITIONS + " FROM " 
    + DB_TABLE + " " + builder.toString(), symptoms); 

這個查詢:

return myDataBase.query(true, DB_TABLE, new String[] {"rowid as _id", KEY_CONDITIONS}, builder.toString(), symptoms, null, null, null, null); 

失敗,因爲DISTINCT在看 ID和狀態欄。這是等價的:SELECT DISTINCT(_id, conditions) ...你,很明顯,只希望不同的條件......

+0

很明顯,我想要明確的條件。請參閱我的更新文章關於我的表記錄 – 2013-03-02 15:10:44

+0

我試圖在SQLite瀏覽器中執行此查詢:選擇DISTINCT條件FROM tblsymptoms其中症狀='胸部疼痛'或症狀='頭暈'它顯示不同的條件。我想知道爲什麼它不顯示在Android中獨特? – 2013-03-02 15:21:45

+0

您正在使用哪個查詢?你嘗試了上面的'rawQuery()'嗎? query()失敗,因爲它的SQL等價物是:'select DISTINCT(rowid,conditions)FROM tblsymptoms where ...'。注意區別? – Sam 2013-03-02 15:27:48

0

你有兩個通用方案二做這個任務 使用行查詢**和** 使用DISTINCT關鍵字

對於使用行查詢您可以直接使用先生的功能。山姆 和使用DISTINCT關鍵字,您可以使用

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

因爲查詢stucher是retuns這樣的:在這段代碼第一個參數是DISTINCT

query(false, table, columns, selection, selectionArgs, groupBy, 
      having, orderBy, null /* limit */); 

所以將它作爲true。 所以你query會喜歡,如果它apperase一個以上的時間返回列名僅此一次

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

基本上DISTINCT關鍵字。