检测数据何时更改

时间:2013-09-20 11:17:43

标签: mysql sql

这是我的数据结构:

name          value          date_received
foo           100            2013-09-19 10:00:00
bar           200            2013-09-19 10:00:00
foo           100            2013-09-19 10:05:00  //no change
bar           200            2013-09-19 10:05:00  //no change
foo           110            2013-09-19 10:08:00  // foo changed          
bar           200            2013-09-19 10:08:00  // no change
......

问题:
我想要一个查询(mysql),它可以做类似的事情:

select date_received where anyOf(foo, bar) changed from the previous 
specified value in the past N hours. 

表中可能还有其他名称,但我们只对foo和bar感兴趣。

任何指针。对我来说,看起来我们需要一个自我加入 - 但不知道如何。

编辑:看起来像下面的查询只是一个很好的起点。

select date_received from (SELECT DISTINCT name, value from data) a 
  INNER JOIN (select DISTINCT name, value, date_received from data)b 
    on (a.name=b.name and a.value=b.value)

更新看起来以下查询有效 - 比我想象的要容易。

SELECT DISTINCT a.tr FROM (
   SELECT name, value, MAX(date_received) dr from data 
    where date_received > now() - INTERVAL 2 hour 
    GROUP BY name, value order by dr desc)a;

1 个答案:

答案 0 :(得分:1)

我看不到您编辑的查询如何解决问题。例如,“最后N小时”在哪里?

我会通过查看先前的值,然后使用围绕日期时间约束和值更改的逻辑来查看是否存在更改。您的问题含糊不清:您是否仅在过去N小时内查找更改?您是否正在寻找N小时前的最后一次值的变化?如果值变回,会发生什么?

但是,所有这些都可以通过在每一行上使用前一个值和上一个时间来回答。以下是如何获得此内容的示例:

select t.*,
       (select t.date_received
        from t t2
        where t2.date_received < t.date_received and
              t2.name = t.name
        order by t2.date_received desc
        limit 1
       ) as prev_date_received,
       (select t.value
        from t t2
        where t2.date_received < t.date_received and
              t2.name = t.name
        order by t2.date_received desc
        limit 1
       ) as prev_value
from t
having <your logic goes here for the date time and changes you care about>;

这是使用having子句而不是子查询,只是为了方便(其他数据库不支持)。

例如,如果您想在过去N小时内进行任何更改:

having date_received > now() - interval N hour and prev_value <> value
相关问题