我试图提高下面的sql代码的速度。现在加载时间约为0.662秒。问题是我需要为所选月份的每一天循环此代码,然后31 * 0.662秒~30秒是加载的长时间。
select fname,lname,(TIME_TO_SEC(TIMEDIFF(r.edate,r.sdate))-r.break) as TotalDiff from tbluser u LEFT JOIN
tblregtime r
on (r.userid = u.id and
r.projectid = 21
and sdate='2013-11-27'
)
INNER JOIN tblgroup_users gU ON gU.userID = u.id
INNER JOIN tblgroup_brukare gB on gB.tblGroupID=gU.tblGroupID where (gB.tblprojectID = 21 AND (gU.status=0 OR gU.status=2))
order by u.fname ASC,u.lname ASC
答案 0 :(得分:0)
不是每天运行31次sql查询,而是可以尝试运行所有日期的单个查询并在代码中适当地处理它们(php或其他)。
这是您的查询的建议替代,它只运行一次(您可能需要稍微改写一下)。你可以尝试一下,让我们知道需要多长时间?此外,为了进一步优化,发布您的查询计划,并可能创建一个sql小提琴将是有帮助的。
select fname,lname,(TIME_TO_SEC(TIMEDIFF(r.edate,r.sdate))-r.break) as TotalDiff, sdate
from tbluser u
LEFT JOIN tblregtime r on (r.userid = u.id and r.projectid = 21 and sdate between '2013-11-01' and '2013-11-31')
INNER JOIN tblgroup_users gU ON gU.userID = u.id
INNER JOIN tblgroup_brukare gB on gB.tblGroupID=gU.tblGroupID where (gB.tblprojectID = 21 AND (gU.status=0 OR gU.status=2))
order by sdate ASC, u.fname ASC,u.lname ASC