Here is a MySQL table, which has three rows.

ram cpu
  1   2
  4   8
  8  16

if I give input as ram=7 and cpu=9,

the query has to smartly select the closest row based on the two input values and return me a single row.

example result which I expect for 7,9 combination:

ram cpu
4    8

is this possible to achieve?

Consider me having thousands of combinations like this. I need a query that always smartly returns a single row.

  • 1
    Hello. You should specify do you mean by the closest. Is it the row with minimal (abs(ram-given_ram) + abs(cpu - given_cpu))? – User5468622 Nov 7 at 14:06
  • Same weight? (Or is CPU more or less important than RAM?) – jarlh Nov 7 at 14:09
  • The row contains which is Closest of these two inputs. – Frank DS Nov 7 at 14:17

You never gave us an exact heuristic for what "closest" means, given that there are two columns involved. Assuming you can accept the record whose sum of absolute difference from the two input values in smallest, then here is one way:

SELECT ram, cpu
FROM yourTable
    ABS(ram - 7) + ABS(cpu - 9)


  • 1
    @Strawberry Well, pi contains the digit 8, so that's definitely one source! – Tim Biegeleisen Nov 7 at 14:09
  • From input box in my web app – Frank DS Nov 7 at 14:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.