Within a piece of code I'm refactoring, a while loop iterates through a result set from a database query and performs a subset of queries.
In most cases, these loops can be extracted to perform fewer queries with a larger set of passed parameters.
However, I'm not sure how to handle this specific query where an ORDER BY and LIMIT 1 make ita little trickier to work out how to optimise it. Any points would welcome on how to approach this query type:
Example:
$e = array( ... );
foreach($e as $i=>j) {
$sql = "SELECT a FROM b WHERE c = '".(int)$j."' ORDER BY f LIMIT 1";
$res = $db->query($sql);
}
A possible way would be to select without the ORDER/LIMIT conditions and filter in PHP via PHP loops but only 1 query, but is there a better way to reduce the result set returned?
EDIT: To clarify better, I'm extending with some more information. If there are 5000 records that would otherwise be returned in the simplified structure above, then we'd need 5000 in the final result set as well after optimising the query out of the loop. The LIMIT 1 clause doesn't allow that to be done in the outer SQL, but I haven't worked out a way to do that with an inner query or sub query yet. It was this element that I wanted to sanity check with better/more experienced minds.
Any pointers welcome! Thank you