penven

博客园 首页 新随笔 联系 订阅 管理
/*
 * 当数据有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;
 * */

思路二:

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 查询的时候,如果你的字段有索引的话,它是霍州索引的!

 

posted on 2017-01-17 15:56  penven  阅读(246)  评论(0编辑  收藏  举报