ORDER BY减慢mysql查询

时间:2018-11-27 11:06:46

标签: mysql

我们有一个查询,它拖慢了整个过程。

此查询大约需要10 seconds

SELECT tbl_organisation.*,  
(
    SELECT count(*)
    FROM tbl_user_organisation 
    WHERE tbl_user_organisation.organisation_id = tbl_organisation.id
) as members 
FROM tbl_organisation
WHERE tbl_organisation.archived = 0 
AND tbl_organisation.name LIKE "%name%"  
ORDER BY members
LIMIT 10 OFFSET 0;

没有ORDER BY的情况下只需要76ms

SELECT tbl_organisation.*,  
(
    SELECT count(*)
    FROM tbl_user_organisation 
    WHERE tbl_user_organisation.organisation_id = tbl_organisation.id
) as members 
FROM tbl_organisation
WHERE tbl_organisation.archived = 0 
AND tbl_organisation.name LIKE "%name%"  
LIMIT 10 OFFSET 0;

我知道第二个仅占用前10行并完成,第一个必须在选择10行之前首先对整个数据集进行排序。

现在的问题是:是否可以使此查询更快?如果可以,怎么办?

由于members是动态计数的,因此我们无法像其他解决方案中建议的那样添加INDEX来加快查询速度。

EXPLAIN的慢查询

enter image description here

1 个答案:

答案 0 :(得分:1)

不一定是答案,但是评论太久了...

此查询告诉我们与名称模式匹配的10个最受欢迎的活动组织,对吧?

换句话说,它在功能上等同于:

SELECT o.*
     , COUNT(*) members
  FROM tbl_organisation o
  JOIN tbl_user_organisation uo
    ON uo.organisation_id = o.id
 WHERE o.archived = 0
   AND o.name LIKE "%name%" -- this is the slow bit in this query
 GROUP
    BY o.id 
 ORDER
    BY members ASC 
 LIMIT 10