我有一个程序直接将我的MQTT消息保存到mySQL数据库中。 我保存有效负载,主题和创建时间。 我有不同的主题,遵循一定的顺序。
我有'主题:开始,主题:带有效负载的阶段1:A,主题:带有效负载的阶段2:B和主题:停止'。在此期间,我有大量的消息与恒定的温度数据馈送。
我看起来像这样:
| Topic | Payload | Create_time |
| 'start' | | '2016-05-17 10:00:00' |
| 'temperature' | 5 | '2016-05-17 10:00:20' |
| 'temperature' | 6 | '2016-05-17 10:01:20' |
| 'temperature' | 6 | '2016-05-17 10:02:20' |
| 'temperature' | 7 | '2016-05-17 10:03:20' |
| 'temperature' | 8 | '2016-05-17 10:04:20' |
| 'phase1' | 'A' | '2016-05-17 10:04:30' |
| 'temperature' | 8 | '2016-05-17 10:05:20' |
| 'temperature' | 9 | '2016-05-17 10:06:20' |
| 'temperature' | 10 | '2016-05-17 10:07:20' |
| 'phase2' | 'B' | '2016-05-17 10:08:30' |
| 'temperature' | 10 | '2016-05-17 10:08:50' |
| 'stop' | | '2016-05-17 10:08:30' |
... more sequences like this where A and B are sequence specific
现在我想查询这些数据,使其成为这种格式:
| Date | Phase1 | Start sequence | End sequence | Phase2 |
| '2016-05-17' | 'A' | '2016-05-17 10:00:00' | '2016-05-17 10:08:30' | 'B' |
...
for every sequence where
- date is the date of that sequence (without time).
- the var A of that sequence
- the start create_time of that sequence
- the end create_time of that sequence
- the var B of that sequence.
如何将不同的行分组为序列,变量在开始和结束时间之间显示为有效负载?
答案 0 :(得分:1)
您可以使用user defined variable标记序列(只要看到Topic='start'
,就会递增):
select date(min(Create_time)) `Date`, group_concat(if(Topic='phase1',Payload,null)) Phase1,
min(Create_time) `Start sequence`,
group_concat(if(Topic='stop',Create_time,null)) `End sequence`,
group_concat(if(Topic='phase2',Payload,null)) Phase2
from (
select if(Topic='start',@id:=@id+1,@id) id, a.*
from (
select *
from Table1
order by Create_time) a
join (select @id:=0) b) a
group by id;