mysql - 使用 Order By 的慢 SQL 查询

标签 mysql sql-order-by explain

我远不是 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/

相关文章:

mysql - 测试登录系统是否被sql注入(inject)保护

python - 如何将参数传递给 QThread Worker 类?

mysql - 如何在 SQL 中找到列的模式?

MySQL - 如何有效地对多列进行分页排序

postgresql - 使用多个连接加速 Postgresql 查询

PHP:更新除空白字段之外的所有内容

sql-server - sql server 命令奇怪,负字符

mysql - 如何在 MySQL 中按关联表中的匹配数对行进行排序?

sql - ORACLE:解释插入计划

使用文件排序的MySQL慢查询