2013-03-02 109 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关键字。