Mysql限制子句不适用于group by的查询

时间:2014-03-11 16:18:10

标签: mysql pdo

以下查询在限制子句不存在时有效。当我尝试使用限制时,不返回任何行。如何对此查询的最终结果集施加限制?

 $testsQuery = "
        select
            testingsession.closed,
            testingsession.id as sessionid,
            testingsession.submittedTests submitted,
            schoolaccount.NameOfSchool as schoolname,
            schoolaccount.ContactEmail as email,
            testtitle,
            date_format(testingsession.createddate, '%%m/%%d/%%Y') as createddate,
            date_format(testingsession.expires, '%%m/%%d/%%Y') as expires,
            credits,
            count(testtaker.id) as completed,
            credits - count(testtaker.id) as available,
        case
            when reporting.sessionid is null then 0
            else 1
        end as reportexists
        from
            schoolaccount
        right join testingsession
        on
            schoolaccount.id = testingsession.schoolid
        inner join thetest
        on
            testingsession.testid = thetest.id
        left outer join testtaker
        on
            testtaker.sessionid = testingsession.id
        left outer join reporting
        on
            testingsession.id = reporting.sessionid
        where %s    
        group by
            testingsession.id
        order by
            createddate DESC
        limit :l1, :l2

    ";

    $where = "1 = 1";
    if(isset($_POST['page'])){
        $pageBegin = 20 * $_POST['page']; 
        $pageEnd = 20 * ($_POST['page'] + 1);
    }else{
        $pageBegin = 0; 
        $pageEnd = 20;
    }
    if(isset($_POST['go'])){
        if(isset($_POST['zip']) && $_POST['zip'] != "zip code"){
            $where = "schoolaccount.zip = :zip or schoolaccount.mailingzip = :zip ";

            $testsStmt = $dbh->prepare(sprintf($testsQuery, $where));

            $testsStmt->bindParam(':zip', $_POST['zip']);
        }else if(isset($_POST['city']) && $_POST['city'] != "city"){
            $where = "schoolaccount.city = :city or schoolaccount.mailingcity = :city ";

            $testsStmt = $dbh->prepare(sprintf($testsQuery, $where));

            $testsStmt->bindParam(':city', $_POST['city']);
        }else if(isset($_POST['state'])){
            $where = "schoolaccount.state = :state or schoolaccount.mailingstate = :state ";

            $testsStmt = $dbh->prepare(sprintf($testsQuery, $where));

            $testsStmt->bindParam(':state', $_POST['state']);
        }
    }else{

        $testsStmt = $dbh->prepare(sprintf($testsQuery, $where));
    }

    $testsStmt->bindParam(':l1', $pageBegin, PDO::PARAM_INT);

    $testsStmt->bindParam(':l2', $pageEnd, PDO::PARAM_INT);

    $testsStmt->execute();

    $testResults = array();
    while($i = $testsStmt->fetch(PDO::FETCH_BOTH)){
        $testResults[] = $i;
    }

1 个答案:

答案 0 :(得分:3)

正如您在this question中看到的那样,请尝试使用:

$testsStmt->bindValue(':l1', (int) trim($pageBegin), PDO::PARAM_INT);
$testsStmt->bindParam(':l2', (int) trim($pageEnd), PDO::PARAM_INT);