6

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

4

3 回答 3

16

您可以使用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 变大时它会溢出。

于 2012-03-12T22:17:12.270 回答
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);
于 2011-08-19T09:03:26.743 回答
1

根据我的研究,我想在@JosephL 的 答案中添加一些内容:

我有两个具有以下值的ArrayList :

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

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

处理后打印如下:

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

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

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

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

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

希望它会有用。谢谢。

于 2016-11-18T06:57:42.110 回答