Mysql calculates the number of query results while obtaining the query results

Source: Internet
Author: User

For some database queries, you not only want to get the query results, but also want to conveniently count the number of records in the query results. My usual practice is:
$ Q = "select * from $ fromTable where $ where limit $ start, $ pageSize ";
$ R = mysql_query ($ q );
$ Q = "select count (*) from $ fromTable where $ where ";
$ Cnt = mysql_query ($ q );

When
However, you can use mysql_num_rows () or mysql_affected_rows () to obtain the number of records after the first query, but both functions return a query.
The number of results is affected by the limit statement. In many cases, you need to know the total number of results of this query statement without limit, such as paging query.

Mysql
In itself supports a better way to achieve the above effect, that is, using SQL _CALC_FOUND_ROWS and FOUND_ROWS () functions. See http:
// Dev.mysql.com/doc/refman/5.0/en/information-functions.html?function_found-rows
Example:

Mysql>SELECT SQL _CALC_FOUND_ROWS * FROMTbl_name
->WHERE id & gt; 100 LIMIT 10;
Mysql>SELECT FOUND_ROWS ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.