Can any one advise me of a problem im having with ordering results in mysql
The Problem
Can not order by any column other than distance
SELECT * , ( ( ( ACOS( SIN( ( '56.3168322' * PI( ) /180 ) ) * SIN( ( `lat` * PI( ) /180 ) ) + COS( ( '56.3168322' * PI( ) /180 ) ) * COS( ( `lat` * PI( ) /180 ) ) * COS( ( ( '-5.414989099999957' - `lng` ) * PI( ) /180 ) ) ) ) *180 / PI( ) ) *60 * 1.1515 * 1.609344 ) AS `distance` FROM `incidents` HAVING `distance` <=3 ORDER BY `distance` ASC LIMIT 0 , 30 When I try to order column based on date in the date_incident row for example
SELECT * , ( ( ( ACOS( SIN( ( '56.3168322' * PI( ) /180 ) ) * SIN( ( `lat` * PI( ) /180 ) ) + COS( ( '56.3168322' * PI( ) /180 ) ) * COS( ( `lat` * PI( ) /180 ) ) * COS( ( ( '-5.414989099999957' - `lng` ) * PI( ) /180 ) ) ) ) *180 / PI( ) ) *60 * 1.1515 * 1.609344 ) AS `distance` FROM `incidents` HAVING `distance` <=3 ORDER BY `date_incidents` ASC LIMIT 0 , 30 In the above it does not sort but still returns results.
Any help would be great on this.
SIN(x),COS(x), etc.) to calculate distances. They are very slow. For larger tables, performance will suffer.HAVINGimplies that some sort of aggregation is going on, I believe. Should theHAVINGbe changed toWHERE distance <=3instead? That may be the problem. I don't see any aggregation going on here. That may be the problem--with thedistancefield in theHAVINGclause, it could be implyingGROUP BY distance.WHEREcan't be used with aliases in the sameSELECT, it can only be used with columns and aliases in tables and subqueries.