I have the following SQL. It's taking about 95 seconds to execute. There are approx 25 million records in the table.
SET @lat=(select latitude from skoovy_prd.pins where user_id=0 and board_id=0 limit 1);
SET @lng=(select longitude from skoovy_prd.pins where user_id=0 and board_id=0 limit 1);
SELECT category_id, MAX(pin_id), pin_id
FROM skoovy_prd.pins
WHERE ( 3959 * acos( cos( radians(@lat) ) * cos( radians( latitude ) )
* cos( radians( longitude ) - radians(@lng) ) + sin( radians(@lat) ) * sin(radians(latitude)) ) ) <=25
GROUP BY category_id DESC
LIMIT 12;
category_id, latitude, longitude, pin_id are all BTREE indexes.
Is there a more efficient way to write this so I can get records back much faster? The purpose of this is to get me a record set of data where each record is a distinct category. I got the sql here after posting this question: mysql selecting records but ensuring data in one column is distinct of which it was marked as a duplicate of Retrieving the last record in each group
There was a solution provided by newtlover in the list of answers which led me to the sql I have written and posted here. (Even though I'm not really looking for the last record in each group, it's at least getting me records where the category_id is distinct in the recordset.
I'm hoping there's a way to improve performance on this query. And if anyone has any suggestions to get around the whole last record in each group, that'd also be appreciated. I am NOT a SQL person by any means, so I'm grasping at straws here.