[英]Optimize mysql subquery containing self-join to reduce CPU Usage
I understand that mysql query involving self-join table might lead to slow query and/or CPU spike, but have been struggling to come up with ways to improve it.我了解涉及自连接表的 mysql 查询可能会导致查询缓慢和/或 CPU 峰值,但一直在努力想出改进它的方法。
CREATE TABLE `tool` (
`tool_id` char(32) NOT NULL,
`provider` varchar(36) NOT NULL,
PRIMARY KEY (`tool_id`),
)
CREATE TABLE `edata` (
`e_data_id` char(32) NOT NULL,
`tool_id` char(32) DEFAULT NULL,
`ref_e_data_id` char(32) DEFAULT NULL,
PRIMARY KEY (`e_data_id`),
KEY `e_ref_e_data__06a0c1a7_fk` (`ref_e_data_id`),
KEY `edata_tool_id_61d6bb9b` (`tool_id`),
CONSTRAINT `e_tool_id_61d6bb9b` FOREIGN KEY (`tool_id`) REFERENCES `tool` (`tool_id`),
)
here is the query in question这是有问题的查询
mutdata
LEFT JOIN (SELECT e1.edata_id as m_id, a1.provider as m_cp from edata e1 INNER JOIN tool a1 on e1.tool_id=a1.tool_id WHERE a1.deleted=0) as mapping
on mutdata.ref_e_data_id=mapping.m_id or mutdata.e_data_id=map.m_id
in short, first the subquery is constructed as a lookup table like a dictionary or map, then mutdata tries to use the lookup table to determine the corresponding provider (this query is part of even larger query).简而言之,首先将子查询构造为像字典或 map 这样的查找表,然后 mutdata 尝试使用查找表来确定相应的提供者(此查询是更大查询的一部分)。 Is there a way to optimize this part?
有没有办法优化这部分?
These indexes may help:这些索引可能会有所帮助:
mutdata: INDEX(ref_e_data_id, e_data_id)
map: INDEX(m_id)
e1: INDEX(tool_id, edata_id)
a1: INDEX(deleted, tool_id, provider)
Try not to use the construct JOIN ( SELECT... )
;尽量不要使用构造
JOIN ( SELECT... )
; instead try to bump that up a level.而是尝试将其提高一个水平。
Do you really need LEFT
in either place?你真的需要
LEFT
在任何一个地方吗?
OR
is terrible for performance. OR
对性能来说很糟糕。 Sometimes it is practical to use two SELECT
connected by UNION DISTINCT
as a workaround.有时使用通过
UNION DISTINCT
连接的两个SELECT
作为解决方法是可行的。 That way, each SELECT
may be able to take advantage of a different index.这样,每个
SELECT
都可以利用不同的索引。
Where is map
in the query?查询中的
map
在哪里?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.