当使用 count(distinct ) 查询运行 select 时,如何加速 mysql 查询
有人可以告诉我如何使用加速这个 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
Can someone please tell me how I can use speed up this mysql query. I know it's currently running slow due to the count(distinct subcontractorRef) syntax. Any other alternatives?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用 JOIN 而不是子查询:
Try this using a JOIN instead of a subquery:
由于我们不知道任何索引,因此猜测。但一个非常常见的错误是没有覆盖 where 子句中所有表的索引。
外部选择的示例:
FROM request_config
其中当前纳税年度=2011
AND 周号 =32
AND ContractorsRef <>132
那么你需要一个索引:
在 request_config(currenttaxyear,weekno,contractorsRef) 上创建索引 mynewIndex
该索引中列的顺序可能会产生很大的差异。所以尝试稍微改变一下它们。
A guess since we dont know any indexes. But a very common mistake is too not have an index covering al the tables in the where clause.
example from your outer select:
FROM request_config
WHERE currenttaxyear =2011
AND weekno =32
AND contractorsRef <>132
Then you need an index:
create index mynewIndex on request_config(currenttaxyear,weekno,contractorsRef)
the order of the columns in that index can make a big difference. So try to change them around abit.