如何计算所有记录,但仅检索(限制)一个要显示的数字? [英] How to count all records but only retrieve (LIMIT) a specific number for display?
问题描述
我只想回显前10行,但是我需要计算受查询影响的总行数.
I want to echo only the first 10 rows, but I need to count the total number of rows affected by the query.
我正在做LIMIT 10
,然后算上一个明显的问题,我一直保持10作为计数.
I was doing a LIMIT 10
and then counting with the obvious problem I kept getting 10 as the count.
什么是正确的方法?
$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'];
}
推荐答案
MySQL对这种事情有一些特殊的支持.首先,在您的SELECT中添加SQL_CALC_FOUND_ROWS
:
MySQL has some special support for this sort of thing. First, include SQL_CALC_FOUND_ROWS
in your SELECT:
SELECT SQL_CALC_FOUND_ROWS *
FROM Badges
WHERE UID = '$user'
ORDER by Date DESC
LIMIT 10 -- Or whatever
Then pull out your rows and then immediately look at FOUND_ROWS()
like this:
SELECT FOUND_ROWS()
获取与原始查询匹配的行数,而无需考虑LIMIT子句.
to get the number of rows that matched your original query without considering the LIMIT clause.
这是特定于MySQL的,但比执行两个查询要快一点.
This is MySQL-specific but it should be a little faster than doing two queries.
这篇关于如何计算所有记录,但仅检索(限制)一个要显示的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!