Hi Guys,
I was wondering if anybody would have some input on how I could possibly optimize this MySQL query. I think I'm doing the right thing with indexes so don't think I can get this query any faster (it's currently taking more than 3 seconds to run) but would really love somebody with more experience to prove me wrong.
Here's the query:
SELECT `rooms`.*,
((IFNULL(SUM(av.host_daily_price), 0) +
rooms.host_daily_price * (4 - COUNT(DISTINCT av.id))) / 4) / 1 as 'price',
rooms.*,
(ACOS(least(1, COS(0.7115121627883911) * COS(1.291278129536698) *
COS(RADIANS(rooms.lat)) * COS(RADIANS(rooms.lng)) +
COS(0.7115121627883911) * SIN(-1.291278129536698) *
COS(RADIANS(rooms.lat)) * SIN(RADIANS(rooms.lng)) +
SIN(0.7115121627883911) * SIN(RADIANS(rooms.lat)))) * 3963.19) AS distance
FROM `rooms`
LEFT JOIN availabilities AS av
ON (av.room_id = rooms.id AND
av.date BETWEEN '2010-12-29' AND '2011-01-01')
WHERE (rooms.deleted_at IS NULL) AND
(`rooms`.`hidden` = 0) AND
(rooms.id <> 7713) AND
(rooms.city_id = 1 AND
rooms.max_guests >= 4 AND
rooms.minimum_stay <= 3 AND
rooms.room_type IN ('room','apartment','house')) AND
(av.inquiry_id IS NULL)
GROUP BY rooms.id
HAVING SUM(IFNULL(status, 0)) = 0 AND
(COUNT(*) = 4 OR `rooms`.default_available = 1)
ORDER BY distance ASC
LIMIT 12;
The output of Explain:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE rooms ref PRIMARY,index_rooms_on_city_id,index_rooms_on_room_type,index_rooms_on_city_id_and_updated_at index_rooms_on_city_id 5 const 2412 Using where; Using temporary; Using filesort
1 SIMPLE av ref index_availabilities_on_room_id,index_availabilities_on_room_id_and_date,index_availabilities_on_room_id_and_date_and_status index_availabilities_on_room_id 5 roomorama.rooms.id 79 Using where
Let me know if any other information would be useful!