如何计算所有记录但只检索(LIMIT)一个特定的数字进行显示?

时间:2011-11-09 04:05:25

标签: mysql pagination

我想只回显前10行,但我需要计算受查询影响的总行数。

我正在做一个LIMIT 10,然后根据显而易见的问题进行计数,我一直计算得到10。

这样做的正确方法是什么?

$data = mysql_query("SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC");
$count = mysql_num_rows($data);

while($row = mysql_fetch_array( $data )) 
    { 
    echo $row['Site'];
    }

4 个答案:

答案 0 :(得分:10)

MySQL对此类事情有一些特别的支持。首先,在SELECT中包含SQL_CALC_FOUND_ROWS

SELECT SQL_CALC_FOUND_ROWS *
FROM Badges
WHERE UID = '$user'
ORDER by Date DESC
LIMIT 10 -- Or whatever

然后拉出你的行,然后立即查看FOUND_ROWS(),如下所示:

SELECT FOUND_ROWS()

在不考虑LIMIT子句的情况下获取与原始查询匹配的行数。

这是特定于MySQL的,但它应该比进行两次查询快一点。

答案 1 :(得分:3)

发出两个查询是非常标准的,一个是使用limit子句选择所需的列,另一个是仅选择一个没有限制的计数。

例如

$countQuery = 'SELECT COUNT(1) FROM Badges WHERE UID = ?';
$limitQuery = 'SELECT * FROM Badges WHERE UID = ? ORDER BY `Date` DESC LIMIT 0, 10';

答案 2 :(得分:0)

你必须进行2次查询:第一次将计算所有行,第二次将返回10行:

$count = 0;
$query = "SELECT count(*) as count FROM Badges WHERE UID = '$user'";
$rs = mysql_query($query);   

if (mysql_errno() == 0)
{
    $r = mysql_fetch_object($rs);
    $count = $r->count;
}

if ($count > 0)
{
    $query = "SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC LIMIT 10";
    $rs = mysql_query($query);      

    if (mysql_errno() == 0)
    {            
        while ($r = mysql_fetch_array($rs))       
        {       
            echo $r['Site']; 
        }     
    }
}

答案 3 :(得分:-1)

统计所有记录

$data = mysql_query("SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC");
$count = mysql_num_rows($data);
echo "No of Records is :" . $count;

打印10条记录......

 $data = mysql_query("SELECT * FROM Badges WHERE UID = '$user' ORDER by Date DESC LIMIT 0, 10");
    while($row = mysql_fetch_array( $data )) 
        { 
        echo $row['Site'];
        }