I'm trying to see if I can speed up this query with an index (or other tweaks). Basically, I want to find the 6 closest records based on Latitude and Longitude in the glinks_Links table.
SELECT
ID, Ville, Title, Telephone, ExpiryDate,
Address, Postal_Code, Latitude, Longitude, priceSort, priceSortBNB, priceSortGITE, has_image,
( 6371 * acos( cos( radians('42.934817491341060000000000000000') ) * cos( radians( Latitude ) ) * cos( radians( Longitude ) - radians('2.222607135772705000000000000000') ) + sin( radians('42.934817491341060000000000000000') ) * sin( radians( Latitude ) ) ) ) AS distance
FROM glinks_Links link
WHERE
link.ExpiryDate < 2147483647
AND isValidated = "Yes"
AND OffersLinkID IS NULL
AND (
((Latitude BETWEEN (42.934817491341060000000000000000 - 35/69.0) AND (42.934817491341060000000000000000 + 35/69.0)) )
AND
(Longitude BETWEEN (2.222607135772705000000000000000 - 35/42.5) AND (2.222607135772705000000000000000 + 35/42.5))
)
HAVING
distance < 25
ORDER BY distance
LIMIT 6
The table structure (remove all the extra stuff thats not in the query, for simplicity), is:
CREATE TABLE `glinks_Links` (
`ID` int(10) UNSIGNED NOT NULL,
`Title` varchar(100) NOT NULL DEFAULT '',
`isValidated` enum('No','Yes') NOT NULL DEFAULT 'Yes',
`ExpiryDate` int(11) NOT NULL DEFAULT '2147483647',
`Address` varchar(100) DEFAULT NULL,
`Postal_Code` varchar(30) DEFAULT NULL,
`Ville` varchar(50) DEFAULT NULL,
`Latitude` decimal(34,30) DEFAULT NULL,
`Longitude` decimal(34,30) DEFAULT NULL,
`OffersLinkID` int(11) DEFAULT NULL,
`priceSortBNB` int(11) DEFAULT NULL,
`priceSortGITE` int(11) DEFAULT NULL,
`priceSort` int(11) DEFAULT NULL,
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
It only takes 0.03 seconds to run, but I have to do it 50k or so time, so it all adds up. Any suggestions are much appreciated :)
UPDATE: I should probably mention I already have some indexes on the table:
ALTER TABLE `glinks_Links`
ADD PRIMARY KEY (`ID`),
ADD KEY `expiryndx` (`ExpiryDate`),
ADD KEY `valexpndx` (`isValidated`,`ExpiryDate`),
ADD KEY `Latitude` (`Latitude`,`Longitude`);