簡體   English   中英

Sqlite查詢一列中的多個值

[英]Sqlite Query for multiple values in one column

我想在表中查詢字段id,其中一些值如1,5,4,11,它們將根據選擇來自前一個屏幕。

cursor = database.query(tablename,
                    new String[] { "TopName" }, "id =?", new String[]{"2,3"}, null, null, null);

當我這樣做時,我得到游標計數0,新的String [] {“2”}我得到的值我想要的所有id的字符串數組中的值像OR那樣在該列中有值。

您可以像這樣使用IN運算符,

cursor = database.query(tablename, new String[] {"TopName"}, "id IN(?,?)", 
                                        new String[]{"2","3"}, null, null, null);

在Android的ContentProvider中使用IN運算符的正確語法如下:

cursor = database.query(contentUri, projection, "columname IN(?,?)", new String[]{"value1" , "value2"}, sortOrder);

或者,我們也可以使用,

cursor = database.query(contentUri, projection, "columnName IN(?)", new String[] {" 'value1' , 'value2' "}, sortOrder);

請注意,我們需要在第二種情況的參數中圍繞每個逗號分隔值使用單引號 ,否則整個字符串將被視為該列的一個值。 SQL會將其視為

SELECT * FROM表WHERE columnName IN('value1,value2')

而不是正確的語法

SELECT * FROM表WHERE columnName IN('value1','value2')

VolkerK是第一個正確回答這個問題的人,但為了完整起見,這里有一個如何使用IN運算符的完整示例:

cursor = database.query(tablename,
                new String[] { "TopName" }, "id IN (?)", new String[]{"2,3"}, null, null, null);

使用IN運算符代替相等比較(=)。

對於SelectionArgs部分,我認為你需要改變:

new String[]{"2,3"}

new String[]{"2","3"}

我想把這個放在這里,因為答案匯編幫助我在SQLiteDatabase.query()放置了多個(未知)值,而one-question-mark對我來說不起作用。 希望幫助任何人

// API > 24
protected String attributesAsMarks(String[] attributes) {
    List<String> marks = Collections.nCopies(attributes.length, "?");

    return marks.stream().collect(Collectors.joining(","));
}

// I'm using API > 15
protected String attributesAsMarks(String[] attributes) {
    StringBuilder sb = new StringBuilder();
    String separator = "";

    for (String s : attributes) {
        if (s == null) continue;

        sb.append(separator).append("?");
        separator = ",";
    }

    return sb.toString();
}

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM