计算出值在mysql数据库中已经存放了多长时间

时间:2018-07-18 09:24:08

标签: mysql

是否存在一个查询,我可以用来计算第一次看到值与运行查询之间的时间差,其中值之间的时间差不超过半小时?因此,例如,例如

--------------------------------------------------
| ID| DATE             | TIME                 |
--------------------------------------------------
| 1 | 18/07/2018       | 10:33:15              |
--------------------------------------------------
| 1 | 18/07/2018       | 10:53:15              |
--------------------------------------------------
| 1 | 18/07/2018       | 11:03:15              |
--------------------------------------------------
| 1 | 18/07/2018       | 11:53:15              |
--------------------------------------------------

结果将是

--------------------------------------------------
| ID|    DATE             | TimePresent           |
--------------------------------------------------
| 1 |    18/07/2018       | 10:33:15              |
-------------------------------------------------- 

因此它可以计算出10:33到11:10之间的时间,因为输入的数据相隔不超过30分钟,并且与11:53相隔很远,因为它与上一次输入的11:03相距30分钟以上 希望我有道理

之后的结果是这样的。

--------------------------------------------
| ID| DATE             | TimePresent       |
--------------------------------------------
| 1 | 18/07/2018       | 00.45             |
--------------------------------------------
| 2 | 18/07/2018       | 24:00             |
--------------------------------------------
| 3 | 18/07/2018       | 45:00             |
--------------------------------------------
| 4 | 18/07/2018       | 72:15             |
--------------------------------------------------

例如

SELECT ID,
       Avg(id 1st seen, now) AS timepresent
FROM database.table
WHERE TIME BETWEEN value inputs < now() - interval 30 MINUTE

如果无法确定输入值之间的时间,那么是否有如下方法?

SELECT ID,
       Avg(id 1st seen, now) AS timepresent
FROM database.table
WHERE date = CURDATE()
GROUP BY ID

Data

1 个答案:

答案 0 :(得分:0)

请参见下面的链接

http://sqlfiddle.com/#!9/486850/81

CREATE TABLE Test (

id int primary key,
Present varchar(10),
Date date,
Time time
);

INSERT INTO Test (id, Present, Date, Time)
Values (1, 'Present', '2018-07-18', '10:13:55' ),
(2, 'Present', '2018-07-18', '10:10:55' );

查询分钟:

SELECT 
id,
Present,
Date,
Time,
Current_Time as CurrentTime,
TIMESTAMPDIFF(MINUTE, time, CURRENT_TIMESTAMP()) AS DifferenceMins
FROM Test

查询hh:mm:ss

SELECT 
id,
Present,
Date,
Time,
Current_Time as CurrentTime,
SEC_TO_TIME(TIMESTAMPDIFF(SECOND, CURRENT_TIMESTAMP(),time)) AS 
TimeDifference
FROM Test

结果:

| id | Present |       Date |     Time | CurrentTime | DifferenceMins |
|----|---------|------------|----------|-------------|----------------|
|  1 | Present | 2018-07-18 | 10:13:55 |    13:33:28 |            199 |
|  2 | Present | 2018-07-18 | 10:10:55 |    13:33:28 |            202 |

我认为这是您要寻找的粗略逻辑。然后,您可以添加要过滤30分钟等的位置。时间是添加数据的时间,而当前时间是执行查询的确切时间。