使用左连接的SQL查询中的LIMIT

时间:2016-02-06 17:23:12

标签: mysql sql pagination left-join limit

我对我的SQL查询读取类别,我们想做分页类别也使用SQL查询给我他们的语句:

public function fetchChildrenNodess($start,$end){
        $q_offset = (int)$start;
        $q_limit = (int)($end - $start);

$query= "select k1.id as id from ".Config::tableKategorie." k1 left join ".Config::tableKategorie."  k2 on k2.nlft<k1.nlft and k2.nrgt>k1.nrgt and k2.nlft>".$this->L." and k2.nrgt<".$this->R." where k1.nlft>".$this->L." and k1.nrgt<".$this->R." and k2.id is null  order by k1.nlft ";

         $i=0; $ret=array();
        // $hash=$this->hash().'_part_'.$start.'_'.$end;


             $Q=mysql_query($query."LIMIT 0, 8 ",CommerceDB::$DB);
             while($R=mysql_fetch_assoc($Q)){
                 $ret[]=new Kategoria($R['id']);

         };

         return $ret;





    }

如果我们在这里使用限制

$Q=mysql_query($query."LIMIT 0, 8 ",CommerceDB::$DB);

所以我只列出了9个subsubcategory并转到下一个子类别。子类别也写了9个类别。我需要让我的列表只包括最多8个结果。好的,谢谢你

1 个答案:

答案 0 :(得分:0)

在此解决方案中,您的函数应该只有1个参数,您可以递增(下一个)或递减(上一个)。我假设您的查询和其他代码工作正常。

页面参数按1-N的顺序排列。如果目标是将记录集限制为最多8行,请不要让用户指定结束值

public function fetchChildrenNodess($page){

   $range_const = 8; // # of rows to show; constant value

   if( $page > 0 ) // what if page is 0 or less ???
       $start = ($range_const * ($page-1)); // start limit
   else
       $start = 0;

   $end = $range_const - $start; // end limit

   $query= "select k1.id as id from ".Config::tableKategorie." k1 left join ".Config::tableKategorie."  k2 on k2.nlft<k1.nlft and k2.nrgt>k1.nrgt and k2.nlft>".$this->L." and k2.nrgt<".$this->R." where k1.nlft>".$this->L." and k1.nrgt<".$this->R." and k2.id is null  order by k1.nlft ";
   $query = $query . ' LIMIT ' . $start . ',' . $end . ';'

   $i=0; $ret=array();

   $Q = mysql_query($query,CommerceDB::$DB);
   while($R=mysql_fetch_assoc($Q)){
       $ret[]=new Kategoria($R['id']);
   }
}

测试用例

+----------+--------+------+
| Page Num | $start | $end |
+----------+---------------+
|    1     |   0    |   8  |
|    2     |   8    |   8  |
|    3     |  16    |   8  |
|    4     |  24    |   8  |
|          |        |      |
|    0     |   0    |   8  |
|   -1     |   0    |   8  |
+----------+--------+------+