[英]Need optimize SQL query
Now i have this query现在我有这个查询
SELECT
d.domain,
r.domain_id,
r.d_lider,
u.email,
u.f_name,
u.l_name,
u.role
FROM (
SELECT r.domain_id,
count(r.id) AS d_lider
FROM bxa_request AS r
WHERE MONTH(r.created) = MONTH(CURRENT_DATE())
AND YEAR(r.created) = YEAR(CURRENT_DATE())
GROUP BY r.domain_id
ORDER BY d_lider
) AS r
LEFT JOIN bxa_user AS u
ON (
u.domain_id = r.domain_id
AND (u.role = 'A' OR u.role = 'E')
)
LEFT JOIN bxa_domain AS d
ON (r.domain_id = d.id )
WHERE r.d_lider = (
SELECT count(*) AS max
FROM bxa_request AS r
WHERE MONTH(r.created) = MONTH(CURRENT_DATE())
AND YEAR(r.created) = YEAR(CURRENT_DATE())
GROUP BY r.domain_id
ORDER BY max DESC LIMIT 1
)
ORDER BY r.d_lider DESC
But if i will check this query with EXPLAIN command i see what query is not optimizely.但是如果我用 EXPLAIN 命令检查这个查询,我会看到哪些查询不是优化的。 Please help me optimize my query http://joxi.ru/DmBEd5puNoVJBr?d=1请帮我优化我的查询http://joxi.ru/DmBEd5puNoVJBr?d=1
I want exclude big count operation from my query, may be join or anything我想从我的查询中排除大计数操作,可能是加入或任何东西
WHERE MONTH(r.created) = MONTH(CURRENT_DATE())
AND YEAR( r.created) = YEAR( CURRENT_DATE())
--> -->
WHERE r.created >= CURDATE() - INTERVAL DAYOFMONTH(CURDATE)-1 DAY
AND r.created < CURDATE() - INTERVAL DAYOFMONTH(CURDATE)-1 DAY + 1 MONTH
That would give an index a chance of being used.这将使索引有机会被使用。
INDEX(created, domain_id)
may help. INDEX(created, domain_id)
可能会有所帮助。
ORDER BY d_lider
in the derived table is ignored.派生表中的ORDER BY d_lider
被忽略。
Please put things that show how tables are related in ON
;请把显示表格如何关联的东西放在ON
; put the rest in WHERE
.把剩下的放在WHERE
。
If LEFT
is not needed, use INNER
;如果不需要LEFT
,请使用INNER
; it could help with optimization.它可以帮助优化。
Please avoid using r
as the alias for both the outer query and a subquery -- it makes it difficult for humans to parse.请避免使用r
作为外部查询和子查询的别名——它使人类难以解析。
Where possible, turn subqueries into JOINs
.在可能的情况下,将子查询转换为JOINs
。
To discuss further, update the Question with whatever changes make sense, and please provide SHOW CREATE TABLE
.要进一步讨论,请使用任何有意义的更改更新问题,并请提供SHOW CREATE TABLE
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.