首页 > 解决方案 > 我需要检测数据库中的所有状态变化

问题描述

我有一组地址,当状态发生变化时,我必须分别检测每个地址。数据库如下所示:TimeSpan、Address、IsBusy。我必须这样做(按时间跨度排序):

Address  IsBusy
610      0
610      1   <--
610      0
750      0
610      0
610      0
750      1   <--
610      1   <--
610      1
750      0
610      0
610      1   <--
750      0
610      0

对于每个地址,我需要检测值 0 变为 1 的位置。

我绝对不知道如何用 SQL 做到这一点谢谢

标签: mysqlsql

解决方案


在旧版本的 MySQL 中,您可以使用相关子查询:

select a.*
from (select a.*,
             (select a2.isbusy
              from addresses a2
              where a2.address = a.address and
                    a2.timespan < a.timestamp
              order by t2.timestamp desc
              limit 1
             ) as prev_isbusy
      from addresses a
     ) a
where a.isbusy = 1 and a.prev_isbusy = 0;

或者:

select a.* from address a where a.isbusy = 1 and (select a2.isbusy from address a2 where a2.address = a.address and a2.timespan < a.timestamp order by t2.timestamp desc limit 1) = 0

这在 MySQL 8+ 中要简单得多:

select a.*
from (select a.*,
             lag(isbusy) over (partition by address over order by timestamp) as prev_isbusy
      from addresses a
     ) a
where a.isbusy = 1 and a.prev_isbusy = 0;

推荐阅读