简体   繁体   中英

SQL Java - Simple query to return 10 rows using cursor

I have a SQLite database with 70 records and would like to get 10 of these records using a cursor.

The 10 records I have have a KEY_ROWID (Primary key) of 2, 3, 15, 23, 35, 50, 51, 60, 61, 64

What is the SQL to retrieve these records?

Here is what I have so far, but I don't think this will work...

Should I be using the WHERE or the HAVING clause?

Any help would be great.

public Cursor getTopTen() {

    String ids = "2, 3, 15, 23, 35, 50, 51, 60, 61, 64";

    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(DATABASE_TABLE);

    String[] columns = new String[] { KEY_ROWID, RECIPE, DESC, PREPTIME,
            COOKTIME, SERVES, CALORIES, FAT, CATEGORY, FAV };

    Cursor myCursor = queryBuilder.query(myDataBase, columns, KEY_ROWID + "="
            + "'" + ids + "'", null, null, null, null);

    return myCursor;
}

In SQL the java above is:

SELECT * FROM myDataBase WHERE KEYROWID = "2, 3, 15, 23, 35, 50, 51, 60, 61, 64".

The SQL should be:

SELECT * FROM myDataBase WHERE KEYROWID IN (2, 3, 15, 23, 35, 50, 51, 60, 61, 64)

When you want to get all rows where a column value is in a specific list of values you have to use the IN operator .

So your code should be:

public Cursor getTopTen() {

    String ids = "2, 3, 15, 23, 35, 50, 51, 60, 61, 64";

    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(DATABASE_TABLE);

    String[] columns = new String[] { KEY_ROWID, RECIPE, DESC, PREPTIME,
            COOKTIME, SERVES, CALORIES, FAT, CATEGORY, FAV };

    Cursor myCursor = queryBuilder.query(myDataBase, columns, KEY_ROWID + " IN ("
            + ids + ")", null, null, null, null);

    return myCursor;
}

在您的情况下,您应该使用WHERE子句而不是HAVING子句。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM