Adam
Adam

Reputation: 20882

MySQL Order Results by Closest Number to Given Number

I'm struggling with a query to select results that are closest to a number. This is for the site www.soulmate.dating

Essentially I have a query that includes the GEO location of each member (besides other data) and I want the results to be Ordered by those closest to the selected GEO location.

This is the Query:

select distance from users;

Note: $this->locationGEO is set by the user (they can pick a place) and it could be 41546

When the results come back if I just order by Distance its not the closed number to value in $this->locationGEO - eg: 41546.

How can I run a query that returns results closed to a number - say 41546.

Rather then order highest to lowest etc.

thx

Upvotes: 3

Views: 776

Answers (1)

TJ-
TJ-

Reputation: 14363

Your query can be something like:

select distance from users order by abs(distance - 41546) asc;

abs is necessary so that the distance is compared on both sides of 41546 (user input).

Upvotes: 4

Related Questions