In our app we use these 3 tables:
- categories
- cities (category_id)
- city_data (distance, city_id)
$q = "SELECT a.id as aid,a.distance as adistance, b.id as bid,b.distance as bdistance FROM city_data as a JOIN city_data as b on a.id != b.id JOIN cities AS a_cities ON a.city_id = a_cities.id JOIN cities AS b_cities ON b.city_id = b_cities.id WHERE (a_cities.category_id='".$_GET["c"]."' AND b_cities.category_id='".$_GET["c"]."') AND abs(a.distance - b.distance) < 100 ORDER BY RAND() LIMIT 1";
The tables cities, city_data has the same count of rows - almost 5.000. The query above takes about 45 seconds, which is terrible. Even the worse thing is, that the tables should have another 5.000 rows, which gives 10.000 rows total...
I would like to ask you about any way, how to reduce the time of execution the query above... 45s is not acceptable...
Do I have any option to solve this issue?
EDIT: Thank you for your advices, I removed ORDER BY RAND() part and the time is really lower, about 22 seconds, but this is still too high for usual using