I have a query in MySQL which runs a stored function on each row of a table and then orders the rows by the result of the function before returning the first 10 rows.
SELECT rowId, MyFunction(x, y, constX, constY) AS funResult
FROM myTable
ORDER BY funResult DESC
LIMIT 10
The problem is that it takes several seconds to run on a table with 10,000 rows which is much too slow. The result of the function can't be computed and stored as another row in the table because it takes a constant which is given by PHP and is different each time the query is run.
The speed of the function itself is not the problem, since removing ORDER BY funResult DESC LIMIT 10
means that the query runs in less than 0.01 seconds.
The problem must be sorting the rows - is there any way this can be done faster, considering the fact that only the first 10 rows are needed?
Update
The simplified function being used calculates the distance between each row and a specified point (where LAT_B and LON_B are constants dependent on the query):
CREATE FUNCTION MyFunction(LAT_A float, LON_A float, LAT_B float, LON_B float)
RETURNS double
DETERMINISTIC
BEGIN
DECLARE tempCalc DOUBLE;
SET tempCalc = 3956 * 2 * ASIN(SQRT( POWER(SIN((LAT_A -abs( LAT_B)) * pi()/180 / 2),2)
+ COS(LAT_A * pi()/180 ) * COS( abs(LAT_B) * pi()/180)
* POWER(SIN((LON_A - LON_B)
* pi()/180 / 2), 2) ));
RETURN tempCalc;
END