3

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

2
  • 1
    Doesn't this work? SELECT a FROM b WHERE c in(1,2,3,4,5) GROUP BY c ORDER BY min(f) Commented Apr 26, 2018 at 23:28
  • Group by c - didn't cross my mind to do it that way. Can you write that as an answer and I'm going to try that out with the data set. This looks like it will do it though! Thanks for another way to look at the problem. Commented Apr 26, 2018 at 23:31

1 Answer 1

3

I think building your query this way should get you the results you are expecting :

SELECT a FROM b WHERE c in(1,2,3,4,5) GROUP BY c ORDER BY min(f);

As GROUP BY will only output a single row of each column "c".

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Lou this is the insight I was looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.