有人可以告诉我如何使用加速这个mysql查询。我知道由于count(distinct subcontractorRef)语法,它目前运行缓慢。还有其他选择吗?
SELECT DISTINCT (contractorsRef) AS cref, RIDGROUP AS ridg,
(select count(DISTINCT subcontractorRef)
FROM request
INNER JOIN request_config ON request_config.RIDGROUP = request.RIDGROUP
WHERE request_config.contractorsRef = outer_config.contractorsRef
AND currenttaxyear =2011
AND weekno =31) AS xxx
FROM request_config outer_config
WHERE currenttaxyear =2011
AND weekno =32
AND contractorsRef <>132
答案 0 :(得分:1)
使用JOIN而不是子查询来尝试:
SELECT
contractorsRef AS cref,
RIDGROUP AS ridg,
IFNULL(T1.subcontractorCount, 0) AS xxx
FROM request_config AS outer_config
LEFT JOIN
(
SELECT
request_config.contractorsRef,
COUNT(DISTINCT subcontractorRef) AS subcontractorCount
FROM request
INNER JOIN request_config
ON request_config.RIDGROUP = request.RIDGROUP
AND currenttaxyear = 2011
AND weekno = 31
GROUP BY contractorsRef
) T1
ON T1.contractorsRef = outer_config.contractorsRef
WHERE currenttaxyear = 2011
AND weekno = 32
AND contractorsRef <> 132
GROUP BY outer_config.contractorsRef
答案 1 :(得分:0)
猜测,因为我们不知道任何索引。但是一个非常常见的错误是没有索引覆盖where子句中的表。 外部选择的例子:
FROM request_config 在哪里currenttaxyear = 2011 AND weekno = 32 AND contractorsRef&lt;&gt; 132
然后你需要一个索引: 在request_config上创建索引mynewIndex(currenttaxyear,weekno,contractorsRef) 该索引中列的顺序可以产生很大的不同。因此,尝试围绕升技改变它们。