1

I have a website where users can look up other users. It is a basic search feature, but I want the users' results to be location based. So maybe they search "David". The basic query for the would be

SELECT * 
FROM   users 
where  fname = 'David' or 
       lname= 'David' 
ORDER BY distance ASC

The problem is that the distance has to be first calculated between each user and the searcher. How can I do this? Not asking to be shown how to calculate distance or anything, just how to logically solve this problem.

John Woo
  • 258,903
  • 69
  • 498
  • 492
user1592953
  • 135
  • 2
  • 9

3 Answers3

2

EDIT: The thing is to calculate the distance directly in your select statement and to order the result based on this calculation.

So if you stored the latitude/longitude in the database, you should be able to do something like that:

$lat = {CURRENT_USER_LATITUDE};
$long = {CURRENT_USER_LONGITUDE};
SELECT users.*,
6371 * 2 * ASIN(SQRT( POWER(SIN(($lat - ABS(users.latitude)) * pi()/180 / 2), 2) + COS($lat * pi()/180 ) * COS( ABS(users.latitude) * pi() / 180 ) * POWER(SIN(($long - users.longitude)*pi()/180 / 2),2))) AS distance
FROM users
ORDER BY distance

And you might have a much simpler query if you're using the geo data types in MySQL.

Nabab
  • 2,608
  • 1
  • 19
  • 32
1

If you are using a calculated field like

select
    someColumn,
    abs(someValue-someValue2)
from 
    myTable

And you need to order by the minimum abs() value you need to add it to the order by clause as follows:

select
    someColumn,
    abs(someValue-someValue2)
from 
    myTable
order by
    abs(someValue-someValue2) asc

Or you can use this syntax:

select
    someColumn,
    abs(someValue-someValue2)
from 
    myTable
order by
    2 asc
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
0

You can do something like:

SELECT users.*, <distance calculation> AS distance
FROM users
WHERE fname = 'David' or
      lname = 'David'
ORDER BY distance ASC
Joe Day
  • 6,965
  • 4
  • 25
  • 26