I’ve been looking for a solution and found sql_calc_found_rows
and found_rows()
.
In the example I used in the question, basically it makes the calculation based on the total number of records found and validates the current page to see if it is larger than the total number of pages calculated. However this can be circumvented using the result of found_rows() subsequently.
** QUERY 1
select sql_calc_found_rows id from TABELA limit ? offset ?
bindValue( $perpage )
bindValue( ( ( $current - 1 ) * $perpage ) )
** QUERY 2
select found_rows() as total
Output
Array
(
[0] => Array( [id] => 4 )
[1] => Array( [id] => 5 )
[2] => Array( [id] => 6 )
)
Array
(
[0] => 16
)
Handbook
mysql> SEELCT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id> 100 LIMIT 10;
mysql> SEELCT FOUND_ROWS();
1) The second select returns a number indicating how many lines the first select would have returned if it had been written without the LIMIT clause.
2) If you are using SELECT SQL_CALC_FOUND_ROWS, Mysql should calculate how many records there are in the complete result set. However, this is faster than executing the query again without LIMIT, because the result set does not need to be sent to the client.
3) SQL_CALC_FOUND_ROWS and FOUND_ROWS() may be useful in situations where you want to restrict the number of rows a query returns, but also determine the number of rows in the complete result set without running the query again. An example is a web script that displays a paged display containing links to pages that show other sections of a search result. Using FOUND_ROWS() allows you to determine how many other pages are required for the rest of the result.
For a long time now, like you, good question +1.
– Jorge B.
@Jorgeb., For small cositas I never had problem, but run 2 querys practically identical and large, I believe that is not the best option. I want to optimize this, because just looking gave me agony :)
– Papa Charlie
I think I could bring the total in the same query using a subquery, but besides being kind of weird, I don’t know if it would bring any improvement in performance.
– Edi. Gomes