I’m trying to decipher this SQL statement. Specifically, what locations z, locations o, locations a mean. What do z o and a mean in this case? Confused 🙁
SELECT o.zip_code
FROM locations z, locations o, locations a
WHERE z.zip_code = #{zip_code}
AND z.zip_code = a.zip_code
AND (3956 * (2 * ASIN(SQRT(
POWER(SIN(((z.latitude-o.latitude)*0.017453293)/2),2) +
COS(z.latitude*0.017453293) *
COS(o.latitude*0.017453293) *
POWER(SIN(((z.longitude-o.longitude)*0.017453293)/2),2)
)))) <= #{distance}
That is a Cartesian Product of the locations table with itself, twice. Since the query is joining the same table with itself it needs to rename each part so that they can be uniquely identified later in the query.
z,o, andaare those names.Look at example two here (http://www.fluffycat.com/SQL/Cartesian-Joins/) to see what is happening. Except in this case there are two cartesian products instead of one. All on the same table.
The query itself could potentially be quite slow since it is doing a double Cartesian product it will create a temporary table with n³ rows and (3m) columns where n is the number of rows in the location table and m is the number of columns.
Edit In response to comment. I’m not positive on this, but after reading your query I believe it is finding all zip codes that are withing a certain distance of another zip code. Itlooks like the third cartesian product (locations a) isn’t even used so you could reduce the query to:
But that still has one Cartesian product. It’d be better if we could get rid of it to:
Will probably be optimized quite well by MySQL