I would like someone to help me to optimize and avoid file sort in the following query. Attached the screenshot of its explain
SELECT DISTINCT(storages.id),
IF(admin_approve = 1
OR storage_free_auctions.user_id = 167
OR ISNULL(storage_free_auctions.user_id),
auction_date, NULL) AS auction_date1
FROM user_list_storage
JOIN storages ON storages.id = user_list_storage.storage_id
JOIN states ON states.id = storages.state
LEFT JOIN storage_auctions ON storage_auctions.id = (
SELECT storage_auctions.id FROM storage_auctions
LEFT JOIN storage_free_auctions
ON storage_free_auctions.storage_auctions_id=storage_auctions.id
WHERE storage_auctions.storage_id = storages.id
AND storage_auctions.status = 'Active'
AND ( ISNULL(storage_free_auctions.user_id)
OR admin_approve = 1
OR storage_free_auctions.user_id = 167)
AND CONCAT(auction_date,' ',start_time) >= CURDATE()
ORDER BY auction_date ASC LIMIT 1)
LEFT JOIN storage_free_auctions
ON storage_free_auctions.storage_auctions_id=storage_auctions.id
LEFT JOIN storage_auction_units
ON storage_auction_units.storage_auction_id = storage_auctions.id
AND storage_auction_units.status='Active'
WHERE storages.storage_status = 'Active'
AND user_list_storage.user_id = 167
AND user_list_storage.user_list_id = 3
AND (storage_free_auctions.user_id = 167
OR admin_approve = 1
OR ISNULL(storage_free_auctions.user_id)
OR user_list_storage.user_id = 167)
GROUP BY storages.id
order by auction_date1
First row of the explain result is as follows.
id : 1
Select_type : PRIMARY
Table : user_list_storage
Type : ref
possible_keys : idx_user_list_id,idx_storage_id,idx_user_id
key : idx_user_id
key_len : 5
ref : const
rows : 64
Extra : Using where; Using temporary; Using filesort