将分页添加到内部联接表

时间:2015-09-23 09:00:03

标签: php mysql paginate

如何使用特定查询添加分页?

这是我的问题:

SELECT emptb.*, tempstore.* FROM (SELECT * FROM emptb WHERE Department = :dept)emptb inner join tempstore 
on emptb.EmpID = tempstore.EmpID WHERE tempstore.ValidDate BETWEEN DATE(:fromDate) AND DATE(:toDate)

注意:当我添加一个paginate时,下一个和上一个按钮不起作用,它被卡在它在表中看到的第一个记录。你可以给我一些好的分页来进行这种查询吗?

1 个答案:

答案 0 :(得分:0)

分页有效,因为您指定了sql子句的限制,但在上面的查询中没有。此外,我发现你现在需要你可以预期的记录总数 - 因此计算!

快速举例,希望这就是你的意思......

$pageNumber=0;
$startRow=0;
$maxRows=10;



$sql="select 
    ( 
        select count(*) from ( select * from `emptb` where `department` = :dept ) emptb 
        inner join `tempstore` on emptb.`empid` = tempstore.`empid` 
        where tempstore.`validdate`
        between date(:fromdate) and date(:todate)
    ) as 'dbrecordcount',
    emptb.*, 
    tempstore.* from ( select * from `emptb` where `department` = :dept ) emptb 
    inner join `tempstore` on emptb.`empid` = tempstore.`empid` 
    where tempstore.`validdate`
    between date(:fromdate) and date(:todate)
    limit $startRow, $maxRows;";


/* above would show the first 10 records */
-> ie: records 0,10


/* Page number is increased by 1 after clicking pagination link / button */
-> $startRow=$pageNumber * $maxRows ~ equals 10;
-> would then show records from 10,20



/* To derive the pagination links, something like this perhaps... */

/* Number of records per page */
$maxRows=10;

/* The total number of expected rows: uses db result 'dbrecordcount' */
$totalRows=$db->dbrecordcount;

/* Current page within paged results: retrieve `page` from querystring if using GET method */
$pageNumber=$_GET['page'];

/* How many pages of results are there */
$totalPages=( $maxRows > 0 ) ? abs( ceil( $totalRows / $maxRows ) - 1 ) : 0;

/* Where does paging begin */
$startRow=$pageNumber * $maxRows;

/* Display pagination links if there are sufficient number of records */
if( $totalPages > 0 && $totalRows > $maxRows ){

    /* First record link */
    if( $pageNumber==0 ) {
        echo "First";
    } else {
        echo "<a href='?page=0'>First</a>";
    }

    /* Previous record link */
    if( $pageNumber > 0 ){
        echo "<a href='?page=".max( 0, $pageNumber - 1 )."'>Previous</a>";
    } else {
        echo "Previous";
    }

    /* Next record link */
    if( ( $pageNumber + 1 ) > $totalPages ){
        echo 'Next';
    } else {
        echo "<a href='?page=".min( $totalPages, $pageNumber + 1 )."'>Next</a>";
    }

    /* Last record link */
    if( $pageNumber==$totalPages ){
        echo 'Last';
    } else {
        echo "<a href='?page=".$totalPages."'>Last</a>";
    }

}