【问题标题】:How to write WHERE IN clause from a dynamic ArrayList for Android SQLite query如何从 Android SQLite 查询的动态 ArrayList 编写 WHERE IN 子句
【发布时间】:2011-10-30 11:01:16
【问题描述】:

如何在 Android SQLite 查询中编写 where in 子句?

检索单个客户的功能

public Cursor getCustomers(int groupId) {
    return db.query(TABLE_CUSTOMERS, new String[] { KEY_CUSTOMER_ID, KEY_NAME}, KEY_GROUP_ID+" = "+groupId, null, null, null, null);
}

检索更多客户的功能

public Cursor getCustomers(ArrayList<Integer> groupIds) {
    // Need to apply SELECT id, name FROM customers WHERE id IN (11, 13, ...18);
    //return db.query(TABLE_CUSTOMERS, new String[] { KEY_CUSTOMER_ID, KEY_NAME}, KEY_GROUP_ID+" = "+groupIds, null, null, null, null);
}

groupId ArrayList 的大小是动态的。

【问题讨论】:

    标签: android sqlite where-in


    【解决方案1】:

    我想根据我的研究在@JosephL's answer 中添加一些内容:

    我有两个 ArrayList 具有以下值:

    First ArrayList(在第一列)具有重复值,Second ArrayList(在第二列)具有唯一值。

    => 67 : 35
    => 67 : 36
    => 70 : 41
    => 70 : 42
    

    处理后都打印如下:

    1. 第一个数组:"(" + TextUtils.join(",", arrayList1) + ")"
    2. 第二个数组:"(" + TextUtils.join(",", arrayList2) + ")"
    3. 第一个数组(使用new HashSet&lt;&gt;(arrayList1) 删除重复项):

      "(" + TextUtils.join(",", new HashSet&lt;&gt;(arrayList1)) + ")"

      => 第一个数组:(67,67,70,70)

      => 第二个数组:(35,36,41,42)

      => 第一个数组(使用 new HashSet&lt;&gt;(arrayList1) 删除重复项):(67,70)

    希望它有用。谢谢。

    【讨论】:

      【解决方案2】:
      return db.query(TABLE_CUSTOMERS, new String[] { KEY_CUSTOMER_ID, KEY_NAME }, KEY_GROUP_ID + " >=" + groupIdsLowLimit + " and " + KEY_GROUP_ID + " <=" + groupIdsUpLimit, null, null, null, null);
      
      String where = "";
      for (int i = 0; i < list.size(); i++) {
          where = where + KEY_GROUP_ID + " =" + list.get(i).toString() + "";
          if (i != (list.size() - 1))
              where = where + " or";
      }
      
      return db.query(TABLE_CUSTOMERS, new String[] { KEY_CUSTOMER_ID, KEY_NAME }, where, null, null, null, null);
      

      【讨论】:

      • 对不起,id 列表可能像 (11, 103, 6, 100)
      【解决方案3】:

      您可以使用Android TextUtils 类连接方法制作一个逗号分隔的 ID 列表以放入 in 子句中。

      String selection = KEY_GROUP_ID + " IN (" + TextUtils.join(", ", groupIds) + ")";
      return db.query(TABLE_CUSTOMERS, new String[] { KEY_CUSTOMER_ID, KEY_NAME}, selection, null, null, null, null);
      

      顺便说一句,如果 groupIds 是另一个表中的主键列表,您应该使用 Longs 来存储它们而不是整数,否则当 ID 变大时它会溢出。

      【讨论】:

        猜你喜欢
        • 2019-08-08
        • 2011-09-09
        • 1970-01-01
        • 2014-01-01
        • 2013-11-13
        • 1970-01-01
        • 2018-09-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多