假设我们有一个像以下的mysql表:
id parent_id date_created previous_status next_status
此表显示parent_id在date_created日期面临状态更改。 如何创建视图或简单查询以显示每个时间段上每个父项的状态。例如:
id parent_id date_created previous_status next_status
1 1 2015-10-11 new old
2 1 2015-10-12 old med
3 1 2015-10-13 med new
...
...
...
结果
parent_id status from_date to_date
1 new null 2015-10-11
1 old 2015-10-11 2015-10-12
1 med 2015-10-12 2015-10-13
1 new 2015-10-13 null
...
...
...
这是一个示例数据库表:Sample audit table
答案 0 :(得分:2)
获得下一个状态的一种方法是使用相关子查询。然后,查询的另一个组件获得初始状态,这表示union all
:
select distinct pid, previous_status as status, null as from_date, date_created as to_date
from t
union all
select pid, next_status, date_created as from_date,
(select date_created
from t t2
where t2.pid = t.pid and t2.date_created > t.date_created
order by t2.date_created desc
limit 1
) as to_date
from t;