SQL查询:这可以在没有嵌套查询的情况下完成吗?

时间:2017-06-21 07:10:53

标签: mysql sql nested-queries

下面的查询有效但计算量很大(有> 14k记录);这可以更有效地完成(例如没有嵌套查询)? 基本上,它匹配同一个表中的实例,这些实例表示具有首先关闭命令(log2)的开启命令(log1)。

Either

谢谢!

2 个答案:

答案 0 :(得分:0)

检查一下。 afaik,where子句比加入on条件效果更好。

SELECT log1.`deviceID`
    ,log1.`timestamp` AS `on`
    ,log2.`timestamp` AS `off`
FROM 
`HC2_log_raw` log1
inner join `HC2_log_raw` log2
on 
log1.`deviceID` = log2.`deviceID`
where
(
    log1.`newValue` > 0
AND log1.`oldValue` = 0
AND log2.`newValue` = 0
AND log2.`timestamp` = (
        SELECT MIN(log3.`timestamp`)
        FROM `HC2_log_raw` log3
        WHERE log3.`timestamp` > log1.`timestamp`
            AND log3.`deviceID` = log1.`deviceID`
            AND log3.`newValue` = 0
        )
)

答案 1 :(得分:0)

您可以尝试将 JOIN GROUP BY MIN 功能一起使用,以存档您的预期结果

SELECT log1.`deviceid`, 
       log1.`timestamp`      AS `on`, 
       MIN(log2.`timestamp`) AS `off` 
FROM   `hc2_log_raw` log1 
       INNER JOIN `hc2_log_raw` log2 
               ON log1.`deviceid` = log2.`deviceid` 
                  AND log1.`timestamp` < log2.`timestamp` 
WHERE  log1.`newvalue` > 0 
       AND log1.`oldvalue` = 0 
       AND log2.`newvalue` = 0 
GROUP  BY log1.`deviceid`, log1.`timestamp`