1

Is there any possibility to make an MySQL statement to select the number if it is less than some value? Lets say I have a php variable: myvar = 123;

And I have some records in database: 120 125 129 121

I want to take all possible database records, where myvar and record difference is less than 5. In this example, it would take 120, 125 and 121. Is it possible to do this? If yes, maybe someone could help me out how?

1
  • please share us code what you have tried yet! Commented Jun 27, 2014 at 7:09

3 Answers 3

3

You can use mysql's BETWEEN operator:

$query = "
SELECT * FROM `table` 
WHERE `record` BETWEEN {$myvar}-5 AND {$myvar}+5";

See mysql demo

Note: BETWEEN will match records between min and max, including min and max. Keep this in mind when developing the logic for your application.

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

1 Comment

Brief, easy and understandable for novice like me! Thanks @Mark M!
1

Try this

SELECT *
FROM `table_name`
WHERE `field` <= your_variable+5
  AND `field` >= your_variable-5

Check SQL Demo

1 Comment

@bereal I mean 123 is stored in user variable I give just example to write constant here
1
SELECT * FROM `table_name` 
WHERE `field_name` BETWEEN (123-4) AND (123+4)


In generalized form as below.
$myvar = 123;
$difference = 5;

$sql = "SELECT * FROM `table_name` 
        WHERE `field_name` BETWEEN ($myvar - $difference +1) AND ($myvar + $difference -1)";

Explanation: ->As mentioned difference should less than 5 .NOT LESS THAN OR EQUAL TO 5.

Lets' Say the required nos are x.

123-x < 5 => 118 < x => 119,120,121,122,123 x-123 > 5 => x > 128 => 127,126,125,124,123

Hence x could be 119 to 127.

=>(123-5)+1 < x < (123+5)-1

Hope this explanation clarifies the sql i wrote above.

Comment if it doesn't solve your problem.

1 Comment

Thank you, very nice solution, but I got an easier one. +1

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.