Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I group on continuous ranges (mysql 5.7)

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.

like image 693
Dr. House Avatar asked Dec 26 '17 00:12

Dr. House


1 Answers

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.

like image 117
Gordon Linoff Avatar answered Oct 13 '22 00:10

Gordon Linoff