如何从动态ArrayList为Android SQLite查询编写WHERE IN子句

时间:2011-08-19 08:58:28

标签: android sqlite where-in

如何在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的大小是动态的。

3 个答案:

答案 0 :(得分:15)

您可以使用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);

BTW如果groupIds是来自另一个表的主键列表,你应该使用Longs来存储它们而不是Integers,否则当ID变大时它会溢出。

答案 1 :(得分:4)

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);

答案 2 :(得分:1)

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

我有两个 ArrayList ,其中包含以下值:

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

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

处理后如下所示打印:

  1. First Array: "(" + TextUtils.join(",", arrayList1) + ")"
  2. 第二阵列: "(" + TextUtils.join(",", arrayList2) + ")"
  3. 第一个数组(使用new HashSet<>(arrayList1)删除重复项):

    <强> "(" + TextUtils.join(",", new HashSet<>(arrayList1)) + ")"

    =&GT;第一阵列:(67,67,70,70)

    =&GT;第二阵列:(35,36,41,42)

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

  4. 希望它会有用。感谢。