Why is the column distance unknown in the where clause of my MySQL query? -
i trying use haversine formula make locator business directory site. query returns error unknown column distance in clause. have no idea why. should work since have defined distance alias directly after haversine formula. ideas?
select l.listing_id id, l.category_id, l.title listing_title, l.description, l.address, l.city, l.zip, unix_timestamp(l.date_submitted) date_submitted, l.latitude, l.longitude, ( 6371 * acos( cos( radians(40.293861) ) * cos( radians( l.latitude ) ) * cos( radians( l.longitude ) - radians(-76.600252) ) + sin( radians(40.293861) ) * sin( radians( l.longitude ) ) ) ) distance, c.category_id cat_id, c.title cat_title, c.slug cat_slug, r.region_id region_id, r.title region_title, r.slug region_slug listings l left join categories c on l.category_id = c.category_id left join regions r on l.region_id = r.region_id distance < 10 order l.date_submitted desc
as said above, can not use alias in clause because value still not known.
what want point out that, query show it, won't scale have more , more rows, since mysql won't have way narrow down number of possible matches.
a approach add condition you'll use define square area having circle area inside. in way sql won't scan whole world, filter rows area "close enough" circle area; , calculate distance lower 10.
for example, if you're looking distance 10 of point x,y; can say
where latitude < (x+5) , latitude > (x-5) , longitude < (y+5) , longitude > (y-5)
this means you're ignoring set of rows, , doing expensive calculations on subset of rows; faster doing expensive calculations on entire dataset.
i hope helps faster , more scalable application.
Comments
Post a Comment