MySQL - Using ORDER BY equals very poor performance -


using mariadb database containing table 1.7m uk postcodes, trying determine nearest postcode given set of latitude , longitude follows:

mariadb [dev]> select count(*) total, postcode, ( 3959 * acos( cos( radians( 53.18526 ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(-3.01984) ) + sin( radians(53.18526) ) * sin( radians( latitude ) ) ) ) distance uk_postcodes limit 1; +---------+----------+--------------------+ | total   | postcode | distance           | +---------+----------+--------------------+ | 1751331 | ab10 1aa | 276.23821854757585 | +---------+----------+--------------------+ 1 row in set (0.35 sec) 

for purpose of example, included count(*) show how many records in table start with. discounting count(*) results in query executing in 0.01 seconds.

i need nearest postcode, add order by statement:

mariadb [dev]> select postcode, ( 3959 * acos( cos( radians( 53.18526 ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(-3.01984) ) + sin( radians(53.18526) ) * sin( radians( latitude ) ) ) ) distance uk_postcodes order distance limit 1; +----------+---------------------+ | postcode | distance            | +----------+---------------------+ | ch5 3pf  | 0.13513453795504218 | +----------+---------------------+ 1 row in set (2.33 sec) 

the correct result returned takes long time.

the google geocode api able return nearest postcode in seems instantly: https://maps.googleapis.com/maps/api/geocode/json?latlng=53.18526,-3.01984

what can return result database instantly?

here's suggestion above in comments in sql code, in case improves performance bit:

    select postcode , min(( 3959 * acos( cos( radians( 53.18526 ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(-3.01984) ) + sin( radians(53.18526) ) * sin( radians( latitude ) ) ) )) distance uk_postcodes group postcode; 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -