Jump to content

Distance calculations inside of a mysql query with joins


dgruetter

Recommended Posts

:confused:

 

Hey,

 

I was wondering if someone can help me with a query I am trying to build. I want to list all nearby cities within a 100 mile radius. I am using a set of tables that are joined and I am trying to calculate the distance inside the query. I am having trouble with the syntax and I am not sure how to reference the fields being calculated. I have something like this:

 


$sql = "SELECT C.Latitude, C.Longitude, C.City, Co.Country, 

(((acos(sin((".$latitude."*pi()/180)) * sin((`Latitude`*pi()/180))+cos((".$latitude."*pi()/180)) * cos((`Latitude`*pi()/180)) * cos(((".$longitude."- `Longitude`)*pi()/180))))*180/pi())*60*1.1515) as distance 

FROM Cities C JOIN Countries Co ON Co.CountryId = C.CountryId WHERE distance <= 100"


 

Do I reference the fields by their aliases in the calculation?

 

A thousand bows if someone can help me. :)

Link to comment
Share on other sites

I did some research and found

 

"You can't use aliases in WHERE conditions, because WHERE clause evaluation precedes the aliases evaluation. "

 

This makes sense. So I changed the query (took out join because I realized I didn't even need it) to:

 

$sql = "SELECT *

 

FROM `Cities`  WHERE (((acos(sin((".$latitude."*pi()/180)) * sin((`Latitude`*pi()/180))+cos((".$latitude."*pi()/180)) * cos((`Latitude`*pi()/180)) * cos(((".$longitude."- `Longitude`)*pi()/180))))*180/pi())*60*1.1515) <= 100";

 

Got a bunch of results. Seems to be working.

Link to comment
Share on other sites

Thanks!

 

I substituted HAVING instead of WHERE and it also worked. Does this save on resources? I am still using the great circle formula but I am trying to find a better one. Any suggestions?

 


$sql = "SELECT Latitude, Longitude, City, (((acos(sin((".$latitude."*pi()/180)) * sin((`Latitude`*pi()/180))+cos((".$latitude."*pi()/180)) * cos((`Latitude`*pi()/180)) * cos(((".$longitude."- `Longitude`)*pi()/180))))*180/pi())*60*1.1515) AS distance

FROM `Cities`  HAVING  distance <= 5";

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.