SQL查詢語句中的 limit offset(轉 )


經常用到在數據庫中查詢中間幾條數據的需求

比如下面的sql語句:

① selete * from testtable limit 2,1;

② selete * from testtable limit 2 offset 1;

注意:

1.數據庫數據計算是從0開始的

2.offset X是跳過X個數據,limit Y是選取Y個數據

3.limit  X,Y  中X表示跳過X個數據,讀取Y個數據

這兩個都是能完成需要,但是他們之間是有區別的:

①是從數據庫中第三條開始查詢,取一條數據,即第三條數據讀取,一二條跳過

②是從數據庫中的第二條數據開始查詢兩條數據,即第二條和第三條。

 

 

----------------------------------------------華麗的分割線----------------------------------------------

以下內容與標題無關

轉載:

參考文獻1.Android操作嵌入式關系型SQLite數據庫

參考文獻2.Android采用ListView實現數據列表顯示

在學習ListView實現數據列表顯示時,需要用到參考文獻1的源代碼,但是源代碼中少了一個getScrollData函數,在此補充一下

 1         /**
 2          * 分頁獲取記錄
 3          * @param offset 跳過前面多少條記錄
 4          * @param maxResult 每頁獲取多少條記錄
 5          * @return
 6          */
 7         //該函數有用到 limit offset可以復習一下
 8         public List<Person> getScrollData(int offset, int maxResult){
 9             List<Person> persons = new ArrayList<Person>();
10             SQLiteDatabase db = dbservice.getReadableDatabase();
11             Cursor cursor = db.rawQuery("select * from person order by id asc limit ?,?",
12                     new String[]{String.valueOf(offset), String.valueOf(maxResult)});
13             while(cursor.moveToNext()){
14                 int id = cursor.getInt(cursor.getColumnIndex("id"));
15                 int age = cursor.getInt(cursor.getColumnIndex("age"));
16                 String name = cursor.getString(cursor.getColumnIndex("name"));
17                 //下面這種也可以獲得參數
18                 /*Integer id = cursor.getInt(0);  
19                         String name = cursor.getString(1);   
20                         Integer age = cursor.getInt(2);  */
21                 persons.add(new Person(id, name, age));
22             }
23             cursor.close();
24             return persons;
25         }        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM