简体   繁体   English

MySQL - 如何从同一个表中减去两个日期时间

[英]MySQL - How to subtract two datetime from the same table

I need help on a small problem with a subtraction in the same table and column我需要帮助解决同一个表和列中的减法小问题

Well, iam creating a view, but the aplication generated the results of used time in tha same table and column.好吧,我正在创建一个视图,但是应用程序在同一个表和列中生成了使用时间的结果。

My table have the following columns: id,field_id,object_id and value_date.我的表有以下列:id、field_id、object_id 和 value_date。

| ID | FIELD_ID | OBJECT_ID | VALUE_DATE          |
| 55 | 4        | 33        | 2016-12-18 19:02:00 |
| 56 | 5        | 33        | 2016-12-18 19:12:00 |
| 57 | 4        | 35        | 2016-12-18 19:30:00 |
| 58 | 5        | 35        | 2016-12-18 20:00:00 |

I do not have much knowledge in sql, but i have tried some functions like timestampdiff, period_siff and others examples in stackoverflow.com.我对 sql 了解不多,但我在 stackoverflow.com 中尝试了一些函数,如 timestampdiff、period_siff 和其他示例。

Someone help me to subtract ID 56 with field_id 5 by line with ID 55 and field_id 4 in object_id 33 in SQL to bring the result in minutes.有人帮我用 SQL 中的 object_id 33 中的 ID 55 和 field_id 4 减去 ID 56 和 field_id 5,以在几分钟内得出结果。 Ex: 10 or 00:10:00例如:10 或 00:10:00

An article about this problem would already help me.一篇关于这个问题的文章已经对我有所帮助。 Thank you very much!非常感谢!

Lets assume that you want result to be in day format then query will be :假设您希望结果为日格式,那么查询将是:

SELECT DATEDIFF(day,startDate,endDate) AS 'Day'  
FROM table1;  

Find complete example here在这里找到完整的例子

The soluction is below:解决方法如下:

select TIMESTAMPDIFF(MINUTE,F1.value_date,F2.value_date) as minutes, F1.value_date,F2.value_date,F1.object_id,F2.object_id,F1.field_id,F2.field_id
from otrs_tst.dynamic_field_value F1 
join otrs_tst.dynamic_field_value F2 on F1.object_id = F2.object_id
 where F1.field_id in ('4','5') 
 and F2.field_id in ('4','5') 
 and F2.field_id <> F1.field_id
 and F1.field_id < F2.field_id
 group by F1.object_id,F2.field_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM