【问题标题】:how to filter multiple data on multiple column sqlite database如何过滤多列sqlite数据库上的多个数据
【发布时间】:2017-11-27 19:57:33
【问题描述】:

我想过滤多个数据,例如

id = "1,3,5" from columnid 有 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);

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

【问题讨论】:

  • 你最好在 stackexchange 中询问与数据库相关的问题
  • @RatanUdayKumar 不,这里合适。因为是编程相关的(查询方法的Android实现)。
  • 如果您要使用普通 SQL(即:rawQuery() 方法),我建议使用类似 SELECT SomeField, SomeOtherField FROM SomeTable WHERE id IN (1, 3, 5) AND Age IN (21, 23, 30) AND Name IN ('a', 'e', 'd') 的方法。我确信使用 query() 方法有一个等价物。但我更喜欢纯 SQL。
  • 好吧,让我试试@Rotwang
  • 谢谢@Rotwang

标签: android database sqlite android-sqlite filtering


【解决方案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','b','c'

【讨论】:

    【解决方案2】:

    我真的很喜欢 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();
    

    【讨论】:

      猜你喜欢
      • 2017-11-03
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-03
      • 2020-04-04
      相关资源
      最近更新 更多