Android SQLite Query - Getting latest 10 records

后端 未结 9 862
死守一世寂寞
死守一世寂寞 2020-12-05 04:56

I have a database saved in my Android application and want to retrieve the last 10 messages inserted into the DB.

When I use:

Select * from tblmessag         


        
相关标签:
9条回答
  • 2020-12-05 05:24

    In your query, the DESC is interpreted as a table alias.

    As mentioned by ρяσѕρєя K, to be able to specify a sorting direction, you need to sort in the first place with an ORDER BY clause.

    The column to be sorted should be a timestamp, if you have one, or an autoincrementing column like the table's primary key.

    0 讨论(0)
  • 2020-12-05 05:29

    Change the DESC to ASC and you will get the records that you want, but if you need them ordered, then you will need to reverse the order that they come in. You can either do that in your own code or simply extend your query like so:

    select * from (
        select *
        from tblmessage
        order by sortfield ASC
        limit 10
    ) order by sortfield DESC;
    

    You really should always specify an order by clause, not just ASC or DESC.

    0 讨论(0)
  • 2020-12-05 05:29
    cursor.moveToLast();
    while (cursor.moveToPrevious()){
           //do something
    }
    

    with same query: select * from tblmessage where timestamp desc limit 10

    0 讨论(0)
  • 2020-12-05 05:31
     "SELECT *  FROM( SELECT *  FROM " + tablename + whereClause + " ORDER BY timestamp DESC LIMIT 10)  ORDER BY timestamp ASC";
    
    0 讨论(0)
  • 2020-12-05 05:33

    Try this,

    SQLiteDatabase database = getReadableDatabase();
    Cursor c=database.rawQuery("sql Query", null);
    if(c.moveToFirst) {
        int curSize=c.getCount()  // return no of rows
        if(curSize>10) {
           int lastTenValue=curSize -10;
           for(int i=0;i<lastTenValue;i++){
              c.moveToNext();
           }
        } else {
           c.moveToFirst();
        }
    }
    

    Then retrieve the last 10 data.

    0 讨论(0)
  • 2020-12-05 05:34

    Slightly improved answer:

    select * from (select * from tblmessage order by sortfield DESC limit 10) order by sortfield ASC;
    

    Michael Dillon had the right idea in his answer, but the example gives the first few rows, inverted order:

    select * ... (select * ... ASC limit 10) ... DESC
    

    He wanted the last, it should be:

    select * ... (select * ... DESC limit 10) ... ASC
    
    0 讨论(0)
提交回复
热议问题