如何对连续范围进行分组(mysql 5.7)

时间:2017-12-26 00:28:20

标签: mysql sql laravel eloquent mysql-5.7

我想返回一个网站关闭时的日期时间范围数组。

我正在使用MySQL 5.7。

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

此处在向下列 - 0(false)表示向下,1(true)表示向上。 我需要一个像这样的观点/结果:

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      

希望这个例子完全代表我的查询需求 - 我只需要停机时间范围。

如果可以使用Laravel(5.5)SQL查询辅助方法实现,那就太棒了(所以我可以很容易地追加像->where('user_id', Auth::user()->id)->whereBetween('created_at', [$range['from'], $range['to']])这样的查询选择器),但在这种情况下我并不挑剔 - 原始MySQL(5.7.19)查询也很棒。

2 个答案:

答案 0 :(得分:4)

如果我理解正确,您可以通过执行以下操作在MySQL中执行此操作:

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;

我不知道如何在Laravel中表达这一点。

答案 1 :(得分:0)

为希望在其mysql查询中实现日期时间范围和user_id选择器的人发布免费答案。这基本上是我的主要目标:

 $range = request('range');
        $range_from = $range['from'];
        $range_to = $range['to'];
        $user_id = Auth::user()->id;
        return DB::select("select user_id, min(created_at) as ca_0, created_at_1 as ca_1
from (select down_time.*,
             (select min(t2.created_at)
              from down_time t2
              where t2.user_id = $user_id and t2.down = 1 and
                    t2.created_at > down_time.created_at and 
                    t2.created_at between '$range_from' and '$range_to'
             ) as created_at_1
      from down_time
      where down_time.down = 0 and down_time.user_id = $user_id and 
      down_time.created_at between '$range_from' and '$range_to'
     ) tt
group by user_id, created_at_1;");