/* * 當數據有50W條的時候,每頁有10條數據, * 用普通的分頁的時候,跳轉到最後一頁,sql語句的執行時間需要900ms左右 * */ //sql語句爲: select id,companyname,contactname,contactmobile,genjintime from crm_customer order by id desc limit 0, 20 /* * 當數據有50W條的時候,每頁有10條數據, * 用這種分頁的時候,每一次跳轉,sql語句的執行時間僅需1ms左右,無論是往最後一頁跳 * */ //查詢上一頁的sql語句爲: select id,companyname,contactname,contactmobile,genjintime from crm_customer where id < $id order by id desc limit 10 if($_GET['prev']) { $sql = "select id,companyname,contactname,contactmobile,genjintime from crm_customer where id < ".$_GET['prev']." order by id desc limit 10"; } else if($_GET['next']) { $sql = "select id,companyname,contactname,contactmobile,genjintime from crm_customer where id > ".$_GET['next']." order by id asc limit 10"; } else { $sql = "select id,companyname,contactname,contactmobile,genjintime from crm_customer order by id asc limit 10"; }*/ $customer = M('customer')->query($sql); if($_GET['prev']) { sort($customer); } $show = ''; if($customer['0']['id']){ $show .= '<a href="/index.php/Home/Page/HighlyPage/prev/'.$customer['0']['id'].'">上一頁</a>'; } if($customer['0']['id']){ $show .= '<a href="/index.php/Home/Page/HighlyPage/next/'.$customer['9']['id'].'">下一頁</a>'; } 注:可是這種分頁有個缺點只能有上一頁,下一頁,不能提供更復雜的跳轉到某一頁的連接 /* * <上一頁 1 2 3 4 5 6 7 8 9 下一頁>」這樣的連接方式 -----若是要這種的連接方式的話----- * 若是LIMIT m,n不可避免的話,要優化效率,只有儘量的讓m小一下,咱們擴展前面作法,仍是SELECT * FROM `table` ORDER BY id DESC, * 按id降序分頁,每頁20條,當前是第10頁,當前頁條目id最大的是9527,最小的是9500,好比要跳到第8頁,我看的SQL語句能夠這樣寫: * SELECT * FROM `table` WHERE id < 9500 ORDER BY id ASC LIMIT 2,20; * 跳轉到第13頁: * SELECT * FROM `table` WHERE id > 9527 ORDER BY id DESC LIMIT 3,20; * */
思路二:php
1、簡單來講,對於分頁的優化就是。。。避免數據量大時掃描過多的記錄。 若是,有條件搜索的話,該怎麼辦呢,這個時候,咱們要知道在用limit 的時候,若是對於有where 條件,又想走索引用limit的,必須設計一個索引,將where 放第一位,limit用到的主鍵放第2位,並且只能select 主鍵! 2、這時候,咱們能夠分兩次來查詢, 第一次:先根據條件查出主鍵id,(把where條件中的字段加上索引),此時,再把id拼接成字符串的形式,再次執行sql查詢 第二次:SELECT * FROM `table` WHERE id in (1,2,3,4,5,6,7,8,9); //這樣的形式 用in 查詢的時候,若是你的字段有索引的話,它是霍州索引的!