I am far from a SQL guru and I am trying to execute:
SELECT `apps`.* FROM `apps`
INNER JOIN `similars`
ON (`apps`.id = `similars`.similar_app_id OR `apps`.id = `similars`.app_id)
WHERE (`similars`.app_id = 542
OR `similars`.similar_app_id = 542)
AND apps.id <> 542
ORDER BY field(`similars`.app_id, 542) desc LIMIT 6
The order by makes it 20x slower than without the order by.
explain extended
SELECT DISTINCT `apps`.*
FROM `apps`
INNER JOIN `similars`
ON (`apps`.id = `similars`.similar_app_id
OR `apps`.id = `similars`.app_id)
WHERE (`similars`.app_id = 542
OR `similars`.similar_app_id = 542) AND apps.id <> 542
ORDER BY `similars`.app_id - 542 desc
Gives me :
+----+-------------+----------+-------------+-------------------------------------------------------------------+-----------------------------------+---------+------+-------+----------+----------------------------------------------------------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+----------+-------------+-------------------------------------------------------------------+-----------------------------------+---------+------+-------+----------+----------------------------------------------------------------------------------------------+ | 1 | SIMPLE | similars | index_merge | index_app_id_and_similar_app_id,index_app_id,index_similar_app_id | index_app_id,index_similar_app_id | 5,5 | NULL | 241 | 100.00 | Using union(index_app_id,index_similar_app_id); Using where; Using temporary; Using filesort | | 1 | SIMPLE | apps | range | PRIMARY | PRIMARY | 4 | NULL | 21493 | 100.00 | Using where; Using join buffer | +----+-------------+----------+-------------+-------------------------------------------------------------------+-----------------------------------+---------+------+-------+----------+----------------------------------------------------------------------------------------------+
I have tried all combinations of indexes on app_id, similar_app_id and composites of those.
Any tips or tricks?
Thanks