没有子查询的MySql查询优化

时间:2013-02-25 15:51:04

标签: mysql sql optimization

有人可以帮我优化此查询吗?

SELECT distinct t.designation,
      (SELECT sum(time_to_sec(timediff(outtime,intime))) 
       FROM onlinetime where datecreated BETWEEN '2012-01-01 00:00:01' 
       AND '2012-12-31 23:59:59' and designation=t.designation) as totsec
FROM onlinetime t;

我正在尝试从在线时间表中获取指定和秒数。它只有8000条记录,但上面的查询需要花费大量的时间来执行。有没有其他方法来优化这个?

2 个答案:

答案 0 :(得分:3)

为什么在您可以直接获得每个指定的总摘要时需要加入表格

SELECT  designation, sum(time_to_sec(timediff(outtime,intime))) totsec
FROM    onlinetime
WHERE   datecreated BETWEEN '2012-01-01 00:00:01' AND '2012-12-31 23:59:59'
GROUP   BY designation

只需在列datecreated上添加索引即可获得更快的效果。

ALTER TABLE onlinetime ADD INDEX (datecreated)

或者你想要这个,

SELECT  a.designation, 
        COALESCE(sum(time_to_sec(timediff(b.outtime,b.intime))), 0) totsec
FROM    onlinetime a
        LEFT JOIN onlinetime b
            ON  a.designation = b.designation AND
                b.datecreated BETWEEN '2012-01-01 00:00:01' AND '2012-12-31 23:59:59'
GROUP   BY a.designation

答案 1 :(得分:0)

正确答案是:

SELECT t.designation,
       sum(case when datecreated between '2012-01-01 00:00:01' AND '2012-12-31 23:59:59'
                then sum(time_to_sec(timediff(outtime,intime)
           end) as totsec
from onlinetime t
group by t.designation

将过滤放在where子句中会忽略原始查询的意图,即将所有“名称”保留在表中。