mysql - 我需要检测数据库中的所有状态变化
问题描述
我有一组地址,当状态发生变化时,我必须分别检测每个地址。数据库如下所示: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 做到这一点谢谢
解决方案
在旧版本的 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;
推荐阅读
- ios - 如何找到所有未指定访问级别的函数?
- c++ - 如何在 I2C 中使用 Arduino 从 LIDAR 的正确地址读取?
- excel - 如何下拉菜单依赖照片粘贴vba excel
- sql - 如何从 Oracle 和 SQLServer 上的数据库中列出模式名称?
- google-calendar-api - 更新用户 responseStatus Google Calendar API
- django - 在 django View 类中访问表单“字段”
- javascript - 如何在 Django 模板中添加排序按钮
- pandas - 为什么数据框列包含附加百分号的数字?
- modelica - 在 Dymola 中显示组件的描述
- java - `kotlinx.coroutines.withContext` 与 Spring WebFlux 一起使用是否安全?