我在构建查询时遇到问题,以获取同一个表中时间字段的两个总和的值。
理想情况下,我希望在日期范围内选择总值,但也可以在MySQL子句中应用日期范围之前得到总数。
我使用子查询构建了下面的内容,但这很慢,并且在8.5秒内完成!
反正有加速吗?
SELECT u.user_id,
u.forename,
u.surname,
c.client_name,
p.project_name,
SUM(t.time_taken) AS total_project_time_between_dates,
(SELECT SUM(st.time_taken)
FROM tbl_mt_tasks st
WHERE st.user_id = u.user_id
AND st.project_id = p.project_id
GROUP BY st.user_id, st.project_id, st.client_id
LIMIT 1) as total_project_time
FROM tbl_mt_tasks t
JOIN tbl_mt_clients c ON t.client_id = c.client_id
JOIN tbl_mt_projects p ON t.project_id = p.project_id
JOIN tbl_mt_users u ON t.user_id = u.user_id
WHERE t.date_created BETWEEN '2015-04-16' AND '2015-04-22'
AND u.status != 100
GROUP BY t.project_id, t.client_id, t.user_id
ORDER BY project_name ASC
答案 0 :(得分:0)
最后的答案似乎已被删除,但实际上是正确的!要过滤掉结果,我只需要使用HAVING子句!
SELECT u.user_id, u.forename, u.surname, c.client_name, p.project_name, SUM(CASE WHEN t.date_created BETWEEN '2015-04-16' AND '2015-04-22' THEN t.time_taken ELSE 0 END) AS total_project_time_between_dates, SUM(time_taken) as total_project_time FROM tbl_mt_tasks t JOIN tbl_mt_clients c ON t.client_id = c.client_id JOIN tbl_mt_projects p ON t.project_id = p.project_id JOIN tbl_mt_users u ON t.user_id = u.user_id WHERE u.status != 100 GROUP BY u.user_id, c.client_id, p.project_id HAVING total_project_time_between_dates > 0 ORDER BY project_name ASC