如何在分页上连续获取Mysql行数


How to get Mysql rownum continously over the pagenation

基本上,我想通过使用@rownum来显示表中的行数,它对第一页很好,但是当我们转到下一页时,我们又从第一行开始。

查询代码:

$sql = "SELECT @rownum:=@rownum+1 as rownum, t.*FROM (SELECT @rownum:=0) r, (select * from tbl) t 
         LIMIT $Page_Start , $Per_Page";

分页代码:

$objConnect = mysql_connect("localhost","user","pass") or die("Error Connect to Database");
`enter code here`$objDB = mysql_select_db("WEB");
$strSQL = "SELECT * FROM line ";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 2; // Per Page
$Page = mysql_real_escape_string($_GET["Page"]);
if(!$_GET["Page"])
{
 $Page=1;
 }
 $Prev_Page = $Page-1;
 $Next_Page = $Page+1;
 $Page_Start = (($Per_Page*$Page)-$Per_Page);
  if($Num_Rows<=$Per_Page)
 {
 $Num_Pages =1;
 }
 else if(($Num_Rows % $Per_Page)==0)
 {
 $Num_Pages =($Num_Rows/$Per_Page) ;
 }
 else
 {
  $Num_Pages =($Num_Rows/$Per_Page)+1;
  $Num_Pages = (int)$Num_Pages;
   }

pagenation用法:

if($Prev_Page)
{
echo "<a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'> Back</a> &nbsp&nbsp;&nbsp; ";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>Next</a> ";
}

所以我希望行数一页接一页地不断增加例如,第1页第1-5行和第2页应该是6-10行,像这样

Thanks to lot

您需要将计算包装在子查询中以获得行号,并将其限制在外部SELECT语句上,以便row_number不会中断,例如,

列名和表名可能与上面的示例不同,但查询的思想是相同的。

SELECT  RowNumber, Student_ID, Student_Name
FROM
        (
            SELECT  @rownum := @rownum + 1 RowNumber,
                    t.*
            FROM    student t, (SELECT @rownum := 0) s
            ORDER   BY t.Student_ID
        ) subQ
// LIMIT    0, 3
  • SQLFiddle Demo (with LIMIT,但在分页中继续)