mysql查询以查找与特定用户关联的序列块的开始和结束(不查找间隙)

vuv7lop3  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(346)

如何编写一个使用这些数据的查询

ID  Timestamp            UID
1   2018-01-01 00:00:00  1
2   2018-01-01 00:00:00  1
3   2018-01-01 00:00:01  1
4   2018-01-01 00:00:01  2
5   2018-01-01 00:00:02  2
6   2018-01-01 00:01:00  2
7   2018-01-01 00:01:02  3
8   2018-01-01 00:02:00  3
9   2018-01-01 00:05:00  1
10  2018-01-01 00:05:01  1
11  2018-01-01 00:05:02  1

把这个还给我:

ID1  ID2  Timestamp1           Timestamp2           UID
1    3    2018-01-01 00:00:00  2018-01-01 00:00:01  1
4    6    2018-01-01 00:00:01  2018-01-01 00:01:00  2
7    8    2018-01-01 00:01:02  2018-01-01 00:02:00  3
9    11   2018-01-01 00:05:00  2018-01-01 00:05:02  1

意思是,我需要得到属于同一个uid的每个序列块的第一个和最后一个时间戳以及第一个和最后一个id(按起始id排序,因为没有重叠),块中不会有id间隙,因为这是一个具有永久不可删除数据的表
谢谢

k2arahey

k2arahey1#

尝试此查询:

SELECT a.*, b.* FROM 
            (SELECT MAX(timestamp) as amax, id, uid FROM `test` GROUP by uid) as a,
            (SELECT MIN(timestamp) as amin, id, uid FROM `test` GROUP by uid) as b

请按表名删除测试。

jexiocij

jexiocij2#

分配一个街区号码是一种方法。下面的查询使用子查询中的变量来执行此操作。

select min(id) minid, max(id) maxid ,blocknumber, min(timestamp) mints, max(timestamp) maxts ,uid
from
(
select t.id,t.Timestamp,t.UID,
        if( t.uid <> @p,@bn:=@bn+1,@bn:=@bn) blocknumber,
        @p:=t.uid p
from t
cross join(select @bn:=0,@p:=0) r
order by t.id,t.uid
) a
group by uid,blocknumber
order by min(timestamp)
;
+-------+-------+-------------+---------------------+---------------------+------+
| minid | maxid | blocknumber | mints               | maxts               | uid  |
+-------+-------+-------------+---------------------+---------------------+------+
|     1 |     3 | 1           | 2018-01-01 00:00:00 | 2018-01-01 00:00:01 |    1 |
|     4 |     6 | 2           | 2018-01-01 00:00:01 | 2018-01-01 00:01:00 |    2 |
|     7 |     8 | 3           | 2018-01-01 00:01:02 | 2018-01-01 00:02:00 |    3 |
|     9 |    11 | 4           | 2018-01-01 00:05:00 | 2018-01-01 00:05:02 |    1 |
+-------+-------+-------------+---------------------+---------------------+------+
4 rows in set (0.08 sec)

相关问题