1. 程式人生 > >mysql中,寫limit得記得排序……

mysql中,寫limit得記得排序……

用mysql的limit進行分頁。。發現竟然有些資料沒顯示在頁面上。。總共才24條資料。楞找不到。。 
後來把語句弄到mysql上查了一下才知道。這條語句中的limit有問題。。有些資料在第二頁被重複顯示了。。 
非常鬱悶。。下面給截圖 
查第一頁的語句 


 

SQL code
SELECT*FROM article a where a.type in (1,2,4) limit 0,20;

第一頁的結果 
(注意紅色部分) 
第二頁的語句 
 

SQL code
SELECT*FROM article a where a.type in (1,2,4) limit 20,20;

結果: 
(注意紅色部分) 
--------------------------------------------------------------------------
後來發現排下序就沒事了。。原來用MySQL的limit必須排序。。唉
這是一位網友給的MySQL Help:
If you use LIMIT row_count with ORDER BY, MySQL ends the sorting as soon as it has found the first row_count rows of the sorted result, rather than sorting the entire result. If ordering is done by using an index, this is very fast. If a filesort must be done, all rows that match the query without the LIMIT clause must be selected, and most or all of them must be sorted, before it can be ascertained that the first row_count rows have been found. In either case, after the initial rows have been found, there is no need to sort any remainder of the result set, and MySQL does not do so.

總結:用limit必須先order by~ 順序是 ------  先 order by ....  再 limit ......