I am using the following query to select the nearest rows to a specified latitude and longitude. The results are then ordered by distance, returning the nearest rows out of the selected data set.
However, I would like to then order the returned nearest rows by the expiry_date field to order that data set so that I will have the ending soonest (nearest expiry date) at the top and furthest at the bottom.
Please can you tell me how I can do this?
SELECT * , ( 6371 * ACOS( COS( RADIANS( latitude ) ) * COS( RADIANS( 51.61062 ) ) * COS( RADIANS( - 0.236952 ) - RADIANS( longitude ) ) + SIN( RADIANS( latitude ) ) * SIN( RADIANS( 51.61062 ) ) ) ) AS distance
FROM `questions`
WHERE `expiry_date` >
CURRENT_TIMESTAMP HAVING distance <=50000
ORDER BY distance
LIMIT 0 , 15
You need a subquery: