选择具有计数的数据>在任何1小时的间隔内1

时间:2016-12-11 12:00:49

标签: mysql sql select count group-by

我正在使用MySql。假设我有一个包含日志的表,如下所示:

+---------+---------------------+------------+
| user_id |      timestamp      |   event    |
+---------+---------------------+------------+
|       1 | 2016-12-11 01:00:00 | some event |
|       2 | 2016-12-11 01:00:00 | some event |
|       2 | 2016-12-11 03:00:00 | some event |
|       3 | 2016-12-11 01:59:00 | some event |
|       3 | 2016-12-11 02:00:00 | some event |
+---------+---------------------+------------+

我想找出同一个用户在1小时间隔内有超过1个日志的情况。

所以,我希望查询返回以下数据:

+---------+---------------------+------------+
| user_id |      timestamp      |   event    |
+---------+---------------------+------------+
|       3 | 2016-12-11 01:59:00 | some event |
|       3 | 2016-12-11 02:00:00 | some event |
+---------+---------------------+------------+

有可能吗?

2 个答案:

答案 0 :(得分:3)

您可以使用exists

select l.*
from logs l
where exists (select 1
              from logs l2
              where l2.user_id = l.user_id and
                    l2.timestamp = l.timestamp and
                    l2.timestamp between date_sub(l.timestamp, interval 1 hour) and
                                         date_add(l.timestamp, interval 1 hour)
            );

注意:要获得两行,您需要在一小时前和一小时后检查。

答案 1 :(得分:1)

select  *
from    t
where   exists
        (
            select      null                
            from        t as t2                
            where       t2.user_id   =  t.user_id
                    and t2.timestamp <> t.timestamp
                    and t2.timestamp between t.timestamp - interval 1 hour
                                     and     t.timestamp + interval 1 hour

        )
;