在MySQL数据库中选择时间轴
这是我的MySQL表在MySQL数据库中选择时间轴,mysql,timeline,mysql-5.5,Mysql,Timeline,Mysql 5.5,这是我的MySQL表 +-----------+-------------+---------------------+ | element | status | hour | +-----------+-------------+---------------------+ | 18 | Available | 2020-01-19 14:23:49 | | 18 | Unavailable | 2019-09-13
+-----------+-------------+---------------------+
| element | status | hour |
+-----------+-------------+---------------------+
| 18 | Available | 2020-01-19 14:23:49 |
| 18 | Unavailable | 2019-09-13 18:19:47 |
| 18 | Available | 2019-09-13 18:18:49 |
| 18 | Unavailable | 2019-09-09 08:22:45 |
| 19 | Available | 2019-09-07 19:13:56 |
| 19 | Available | 2019-09-03 18:13:49 |
+-----------+-------------+---------------------+
通常,此MySQL表中每个元素状态的行时间线不可用/可用
但对于元素编号19,状态行的时间线是可用的:
+----------+-------------+---------------------+
| element | status | hour |
+----------+-------------+---------------------+
| 19 | Available | 2019-09-07 19:13:56 |
| 19 | Available | 2019-09-03 18:13:49 |
+----------+-------------+---------------------+
这意味着异常
我需要截取这些情况,即当时间线可用/可用时,每个元素状态的所有行
如何解决这个问题
你能帮我吗
编辑01
基于最初发布的示例数据,您可以使用子查询查看下一个和上一个状态,然后进行测试
select s.element,s.hour,s.`status`
from
(
select t.*,
(select concat(t1.status,',',t1.hour) from t t1
where t1.element = t.element and t1.hour < t.hour
order by t1.element,t1.hour desc limit 1) prev,
(select concat(t1.status,',',t1.hour) from t t1
where t1.element = t.element and t1.hour > t.hour
order by t1.element,t1.hour limit 1) nxt
from t
) s
where s.status = substring_index(s.nxt,',',1) or
s.status = substring_index(s.prev,',',1)
;
为了避免这种情况,最好将元素、状态作为唯一字段放在该特定字段中table@Zeljka我需要每个元素的历史记录,如果添加唯一字段,则会丢失时间线。谢谢你的数据库版本是什么?@PaulSpiegel 5.5.62 MySQL版本远程主机记录是如何订购的?表中是否还有其他列,如autoincrement ID?因为对于例如元素18,第三个时间戳在第二个时间戳之前。元素19也是一样,那么如何区分这里的顺序呢?谢谢,但我在[Err]1054中有错误-where子句中的未知列“t.element”您没有给出表名,所以我使用了t-替换表名。
select s.element,s.hour,s.`status`
from
(
select t.*,
(select concat(t1.status,',',t1.hour) from t t1
where t1.element = t.element and t1.hour < t.hour
order by t1.element,t1.hour desc limit 1) prev,
(select concat(t1.status,',',t1.hour) from t t1
where t1.element = t.element and t1.hour > t.hour
order by t1.element,t1.hour limit 1) nxt
from t
) s
where s.status = substring_index(s.nxt,',',1) or
s.status = substring_index(s.prev,',',1)
;