2011-08-19 12 views
6

Come posso scrivere la clausola where in nella query SQLite di Android?Come scrivere la clausola WHERE IN da un array ArrayList per Android SQLite query

funzione per recuperare un singolo cliente

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

funzione per recuperare un numero maggiore di clienti

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

La dimensione del groupId ArrayList è dinamico.

risposta

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

scusa, la lista può essere come (11, 103, 6, 100) –

+0

vedere la risposta aggiornata – Rasel

15

È possibile utilizzare la classe Android TextUtils join metodo per fare un elenco separato da virgole di ID di mettere in nella clausola.

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 se groupIds è una lista di chiavi primari di un altro tavolo si dovrebbe utilizzare per memorizzare Longs loro non interi altrimenti si traboccare quando gli ID diventano grandi.

1

voglio aggiungere qualcosa in @JosephL'sanswer come per il mio studio:

Ho due ArrayList con i seguenti valori:

Prima ArrayList (in prima colonna) hanno valori duplicati e Secondo ArrayList (nella seconda colonna) ha valori univoci.

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

stampa sia dopo l'elaborazione come qui sotto:

  1. prima matrice: "(" + TextUtils.join(",", arrayList1) + ")"
  2. seconda matrice: "(" + TextUtils.join(",", arrayList2) + ")"
  3. prima matrice (rimuovere i duplicati utilizzando new HashSet<>(arrayList1)):

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

    => Prima Array: (67,67,70,70)

    => Second Array: (35,36,41,42)

    => prima matrice (rimuovere i duplicati che utilizzano new HashSet<>(arrayList1)): (67,70)

speranza che utile. Grazie.

Problemi correlati