I'm thinking about splitting one query into a count query, and a query that gets everything else. The original query is ugly - temporary tables, filesorts, ...
First I'd get the counts, then do:
while ($result_count <= $needed_results && $row = mysql_fetch_object($result)) {
if($row->Max > $prev_counts_array($row->ID)) {
// do stuff with row
$result_count++;
}
}
So, say the second query would retrieve 100 rows, but you only need 4. Do the other 96 records use resources - or only when they're fetched?