MySQL之分頁limit和排序order by


在項目中經常用到排序和分頁,mysql中這兩個關鍵詞在查詢的時候,也經常用到,現場來玩一下

 

先試試Order by:

  故名思意,order by的意思就是排序,那么就要配合ASC和DESC來使用,ASC是升序,DESC是降序

同樣還是成績表,查出成績,使用降序排列

 select res.studentresult from result res order by res.studentresult DESC;

格式為:select 字段 from 表名 where 條件 order by 排序的字段 ASC/DESC;

 

 select res.studentresult from result res where res.studentresult>80 order by res.studentresult DESC;

加一個條件,查詢大於80的學生的成績,使用降序

 

這個是用升序

 

 

 好,接下來使用一些limit進行分頁,顯示前面五條,0開始

select res.studentresult from result res order by res.studentresult DESC LIMIT 0,5;

格式:select 字段 from 表名 where 條件 order by 排序的字段 ASC/DESC limit 從第幾條開始,一共顯示幾條;

 

這里,我們試一下換成從第一條開始,一頁顯示6條 

 

 很簡單。所以可以看出規律,可以用來分頁時候使用

假設,一頁顯示5條,pagesize

總數量/pagesize得出總頁數

當前頁為N開始

那么(N-1)*pagesize,就得出當前頁起始的條數

舉例:

第一頁的時候:

(1-1)*5=0

select res.studentresult from result res order by res.studentresult DESC LIMIT 0,5;

 

 第二頁的時候:N=2

(2-1)*5=5;

select res.studentresult from result res order by res.studentresult DESC LIMIT 5,5;

 

 如此,實現了分頁。


免責聲明!

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



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