Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a mysql Database and 2 tables let's say clients and schools. Now each table has columns latitude and longitude. And I need do make a SELECT for example from second table where schools are in a given radius of one record from first table. Calculations should be made based on latitude and longitude. PS: I am using PHP.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
341 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can calculate a distance using a Spherical law of cosines:

SELECT DEGREES(ACOS(SIN(RADIANS(clients.latitude)) * SIN(RADIANS(schools.latitude)) + 
                    COS(RADIANS(clients.latitude)) * COS(RADIANS(schools.latitude)) 
                                                   * COS(RADIANS(clients.longitude 
                                                               – schools.longitude)))) 
       * 60 * 1.1515 * 1.609344 AS distance
FROM clients, schools HAVING distance < $radius

RADIANS(X) - degrees to radians
ACOS(X) - the arc cosine of X, that is, the value whose cosine is X
DEGREES(X) - radians to degrees

60 - minutes in a degree
1.1515 - miles in a nautical mile
1.609344 - kilometres in a mile


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...