如何在多列sqlite数据库上过滤多个数据

时间:2017-06-24 09:32:15

标签: android database sqlite android-sqlite filtering

我想过滤多个数据,例如

来自columnid的

id =“1,3,5”,其中包含1到10个id

和另一列如名称

name =“a,e,d”来自10条记录的名称栏

和另一个标准,如年龄

age =“21,23,20”来自同一张表的10条记录的年龄栏, 我得到的一个例子是

Cursor cursor = db.query("TABLE_NAME",new String[]{"ColumnName"}, "ColumnName=?",new String[]{"value"}, null, null, null);

这只是一列,但我想从多列获取数据,任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

试试这个工作示例,

Cursor cursor =
                db.query(TABLE_DIARYENTRIES,
                        new String[] {},
                        STUDENT_ID + " IN ("+resultStudent+")"+ " AND " +CLASS_NAME + " IN ("+resultClass+")"
                                + " AND " +SUBJECT_NAME + " IN ("+resultSubject+")"
                        null, null, null, null);

,您的结果字符串应为' a''''' c'

答案 1 :(得分:0)

我非常喜欢Google's example的结构方式。因为对于像我这样的新手而言,它让我非常清楚自己在做什么。它对SQL注入也更加健壮。以下是我修改过的Google示例版本:

//Column(s) I want returned
String[] projection = {"ColumnIWantReturned"};

//Column(s) I want to filer on
String selection = "FilterColumn1 IN (?) and FilterColumn2 IN (?, ?)";
String[] selectionArgs = {"ArgumentForFilterColumn1", "FirstArgumentForFilterColumn2", "SecondArgumentForFilterColumn2"};

Cursor cursor = db.query(
        "MyTable",   // The table to query
        projection,             // The array of columns to return (pass null to get all)
        selection,              // The columns for the WHERE clause
        selectionArgs,          // The values for the WHERE clause
        null,                   // don't group the rows
        null,                   // don't filter by row groups
        null               // The sort order
);

cursor.moveToFirst();
while (!cursor.isAfterLast()) {
    Log.d("this-is-a-test", cursor.getString(0));
    cursor.moveToNext();
}

cursor.close();