查询限制被忽略

时间:2014-09-25 13:38:09

标签: php pdo sql-limit

我有这段代码,它计算了correct列中的所有行,并且LIMIT 5

被忽略的代码行


$last5rate = $db->prepare("select sum(correct) 
from exams where username = :username ORDER BY testID DESC LIMIT 5");

这是整个代码


<?php

require('includes/config.php'); 

//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); } 
$username = $_SESSION['username'];
$last5rate = $db->prepare("select sum(correct) from exams where username = :username ORDER BY testID DESC LIMIT 5");
$last5rate->execute(array(':username' => $username));
for($i=0; $rows = $last5rate->fetch(); $i++){
    //Edit this row
$last5  = $rows['sum(correct)'];
$last5final = $last5 / 10;
 }
echo $last5final;

?>

我尝试过以下方法


select sum(correct) from exams where username 
= :username ORDER BY testID DESC LIMIT 0,5

select sum(correct) from exams where username 
    = :username ORDER BY testID DESC LIMIT 5

1 个答案:

答案 0 :(得分:9)

LIMIT限制了它返回的结果数量

您的SUM始终会返回1个结果,因此您的限制不会执行任何操作。

你可能需要这样的东西(未经测试,仅举例)

SELECT sum(correct) FROM(
    select correct from exams where username 
    = :username DESC LIMIT 5
)

我删除了订单,根据需要调整它。