简体   繁体   English

MySQL查询优化无子查询

[英]MySql query optimization without subquery

Can anyone help me to optimize this query? 谁能帮助我优化此查询?

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;

I am trying to fetch designation and sum of seconds from onlinetime table. 我正在尝试从在线时间表中获取名称和秒数总和。 It has only 8000 records but the above query taking lot of time to execute. 它只有8000条记录,但是上面的查询要花很多时间才能执行。 Is there any other way to optimize this? 还有其他方法可以对此进行优化吗?

why do you need to join the table when you can directly get their total summary for each designation 当您可以直接获取每个名称的总摘要时,为什么需要加入表格

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

just add an index on column datecreated for faster performance. 只是在列中添加索引datecreated获得更快的性能。

ALTER TABLE onlinetime ADD INDEX (datecreated)

or maybe you want this, 也许你想要这个

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

The correct answer is: 正确的答案是:

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

Putting the filtering in the where clause misses the intention of the original query, which is to keep all "designation"s in the table. 将过滤放在where子句中会失去原始查询的意图,该意图是将所有“名称”保留在表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM