我远不是 SQL 专家,但我正在尝试执行:
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
order by 使它比没有 order by 慢 20 倍。
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
给我:
+----+-------------+----------+-------------+-------------------------------------------------------------------+-----------------------------------+---------+------+-------+----------+----------------------------------------------------------------------------------------------+ | 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 | +----+-------------+----------+-------------+-------------------------------------------------------------------+-----------------------------------+---------+------+-------+----------+----------------------------------------------------------------------------------------------+
我已经尝试了 app_id、similar_app_id 及其组合的所有索引组合。
有什么提示或技巧吗?
谢谢
最佳答案
无论 LIMIT
按未索引字段排序 - 在您的情况下,您对要排序的值进行计算总是需要更长的时间...
我会跳过扣减 542 并为 app_id 添加索引
关于mysql - 使用 Order By 的慢 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5373103/