I want to return an array of date time ranges of when a site is down.
I am using MySQL 5.7.
Table down_time
created_at user_id down
2017-12-15 14:50:21 1 1
2017-12-21 19:19:19 1 0
2017-12-25 22:41:14 1 1
2017-12-25 22:41:17 1 0
2017-12-25 23:11:22 1 0
2017-12-25 23:11:24 1 1
2017-12-25 23:31:24 1 1
Here on down column - 0(false) represents down and 1(true) represents up. I need a view/result like this:
down up user_id
2017-12-21 19:19:19 2017-12-25 22:41:14 1
2017-12-25 22:41:17 2017-12-25 23:11:24 1
Hope this example fully represents my query needs - I only need the down time ranges.
If this is possible to achieve using Laravel(5.5) SQL query helper methods, that would be great(so I can easily append query selectors like ->where('user_id', Auth::user()->id)->whereBetween('created_at', [$range['from'], $range['to']])
), but I am not being picky in this situation - a raw MySQL(5.7.19 ) query would be great as well.
If I understand correctly, you can do this in MySQL by doing:
select user_id, min(created_at) as ca_0, created_at_1 as ca_1
from (select t.*,
(select min(t2.created_at)
from t t2
where t2.user_id = t.user_id and t2.down = 1 and
t2.created_at > t.created_at
) as created_at_1
from t
where t.down = 0
) tt
group by user_id, created_at_1;
I have no idea how to express this in Laravel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With