数据库同表时间间隔差
背景
在统计效率的场景中有发现需要使用到两条数据之间的时间隔,然后所用使用的字段是一致的,所以就需要使用第一条数据的更新时间去与第二条的更新时间做时间差的求值,然后进行显示
思路
- 将表进行时间倒序然后构成一组新的数据(此时只需要进行有用字段的构造),我以上场景只需要时间,所以我就构造时间与id的临时表代码如下
SELECT (@id := @id + 1) AS id, updateTime as "endtime" FROM (SELECT updateTime from patientimages ORDER BY updateTime desc) AS f
- 将以上数据构造出开始时间与结束时间,然后开始时间与结束时间的规律是前一条数据的结束时间是第二条数据的结束时间,所以需要错一位构造开始时间,代码如下:
SET @id := 0; SET @id1 := -1; SELECT t1.id, t1.endtime, t2.id as id2, t2.startime FROM ( SELECT (@id := @id + 1) AS id, updateTime as "endtime" FROM (SELECT updateTime from patientimages ORDER BY updateTime desc) AS f ) as t1 LEFT JOIN( SELECT (@id1 := @id1 + 1) AS id, updateTime as "startime" FROM (SELECT updateTime from patientimages ORDER BY updateTime desc) as f1) as t2 on t1.id = t2.id
- 对数据进行时间差的求值,并按照需求进行展示此处需要用到时间函数,TIMEDIFF(),否则会是数学的十进制进行计算的,具体代码如下
SET @id := 0; SET @id1 := -1; SELECT t1.id, t1.endtime, t2.startime, TIMEDIFF(t1.endtime, t2.startime) as timediff FROM ( SELECT (@id := @id + 1) AS id, updateTime as "endtime" FROM (SELECT updateTime from patientimages ORDER BY updateTime desc) AS f ) as t1 LEFT JOIN( SELECT (@id1 := @id1 + 1) AS id, updateTime as "startime" FROM (SELECT updateTime from patientimages ORDER BY updateTime desc) as f1) as t2 on t1.id = t2.id
- 以上代码成果展示如下:
以上仅作记录