我需要改进我的查询,特别是执行时间。这是我的查询:
SELECT SQL_CALC_FOUND_ROWS p.*,v.type,v.idName,v.name as etapaName,m.name AS manager,
c.name AS CLIENT,
(SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(duration)))
FROM activities a
WHERE a.projectid = p.projectid) AS worked,
(SELECT SUM(TIME_TO_SEC(duration))
FROM activities a
WHERE a.projectid = p.projectid) AS worked_seconds,
(SELECT SUM(TIME_TO_SEC(remain_time))
FROM tasks t
WHERE t.projectid = p.projectid) AS remain_time
FROM projects p
INNER JOIN users m
ON p.managerid = m.userid
INNER JOIN clients c
ON p.clientid = c.clientid
INNER JOIN `values` v
ON p.etapa = v.id
WHERE 1 = 1
ORDER BY idName
ASC
执行时间是aprox。 5秒如果我删除此部分:(SELECT SUM(TIME_TO_SEC(remain_time)) FROM tasks t WHERE t.projectid = p.projectid) AS remain_time
执行时间减少到0.3秒。有没有办法获得 remaining_time 的值,以减少exec.time?
从PHP调用SQL(如果这与任何建议的解决方案相关)。
答案 0 :(得分:2)
听起来你需要tasks
上的索引。
尝试添加以下内容:
create index idx_tasks_projectid_remaintime on tasks(projectid, remain_time);
相关子查询应该只使用索引并且速度更快。
答案 1 :(得分:0)
在编写时优化查询将带来显着的性能优势(见下文)。但是在接近任何优化时要问的第一个问题是你是否真的需要查看所有数据 - 这里没有对结果集进行过滤。这对优化查询的方式产生巨大影响。
在上面的查询中添加索引仅在优化程序在主查询返回的每个行的任务表上打开新游标时才有帮助。在没有任何过滤的情况下,对任务表进行全表扫描会更快 。
SELECT ilv.*, remaining.rtime
FROM (
SELECT p.*,v.type, v.idName, v.name as etapaName,
m.name AS manager, c.name AS CLIENT,
SEC_TO_TIME(asbq.worked) AS worked, asbq.worked AS seconds_worked,
FROM projects p
INNER JOIN users m
ON p.managerid = m.userid
INNER JOIN clients c
ON p.clientid = c.clientid
INNER JOIN `values` v
ON p.etapa = v.id
LEFT JOIN (
SELECT a.projectid, SUM(TIME_TO_SEC(duration)) AS worked
FROM activities a
GROUP BY a.projectid
) asbq
ON asbq.projectid=p.projectid
) ilv
LEFT JOIN (
(SELECT t.project_id, SUM(TIME_TO_SEC(remain_time)) as rtime
FROM tasks t
GROUP BY t.projectid) remaining
ON ilv.projectid=remaining.projectid