Forum Moderators: coopster
My question is this: to handle pagination it appears I need to run two queries. One to run the actual query with ORDER BY and LIMIT. The second to get the COUNT(). Both have the same WHERE clause.
Is there a good way to handle this without running two queries? A few of them have multiple JOINs and that sort of thing. It's working ok now while in development, but ultimately the site should become busier (I hope). It seems like running multiple complex queries is something I want to avoid if possible.
Thanks,
- Ryan
The alternatives would be:
mysql_num_rows($handle)or
count($array), and if it is, you know you can display your 'next>>' link, and all the previous page links you want. If it's not there, don't display the 'next>>'. Some sites with paginated articles seem to use this technique - phpbuilder, iirc for example - you can go ahead to the next page, and on subsequent pages, there are links to each previous page; however, on page 1, you can't go directly to page 3 or page 4.
Also see [webmasterworld.com...] .
Total records that match the WHERE clause is 232.
I ran each query 100 times, so the actual query time is 1% of what I show.
1 - SELECT * FROM table WHERE field LIKE '%searchstring%'
1.4918 seconds. This was just a baseline. It returned all the records, which I didn't want.
2 - SELECT * FROM table WHERE field LIKE '%searchstring%' LIMIT 0, 10
0.2326 seconds, also a baseline - This time it returned the records I wanted to display.
3 - Same primary query as #2, but added: SELECT COUNT(id) FROM table WHERE field LIKE '%searchstring%'.
1.0427 seconds. The primary query returned the 10 records I wanted and the count query returned 232.
4 - SELECT SQL_CALC_FOUND_ROWS * FROM table WHERE field LIKE '%searchstring%' LIMIT 0, 10 - followed by SELECT FOUND_ROWS().
0.8999 seconds. A little more than a 10% increase in speed over using COUNT(x). Like was said above, this requires MySQL v4.
I don't know how useful (or new) this information is to y'all, but I figured I'd try and save anyone the 30 minutes I spent benchmarking :-)
- Ryan
The second query - SELECT FOUND_ROWS() - will return one record with one field. So:
$row = mysql_fetch_array(mysql_query("SELECT FOUND_ROWS()"));
echo $row[0]; - Ryan