Summary of mysql time and date type related operations

1. Addition and subtraction calculation of datetime time type

In the process of brushing the questions, it is necessary to calculate the difference in seconds between the two datetime values, so I directly subtract them:

select
	tag,
	start_time,
	end_time,
	duration,
	end_time - start_time
from tb_user_video_log vl inner join tb_video_info vi on vl.video_id = vi.video_id;

The result came out:
insert image description here

It is obvious that there is a problem with the last data 4100. Baidu combined the official documents. It turns out that the datetime type is directly spliced ​​into integers when doing addition and subtraction calculations. Add and subtract according to the spliced ​​integers. For example, the last piece of data is equivalent to
  20211001110005
- 20211001105905
_______________
= 4100

The solution can be to use the official function TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)to return the difference between parameter 2 minus parameter 1, and the result is in unit, which is end_time - start_timerewritten in the above sql TIMESTAMPDIFF(SECOND,start_time,end_time).
You can also use TIME_TO_SEC(time)the function to convert the time into seconds before adding and subtracting calculations, that is, changing it TIME_TO_SEC(end_time) - TIME_TO_SEC(start_time)to have the same effect.

The usage of mysql built-in functions can be viewed by ctrl+f in https://dev.mysql.com/doc/refman/8.0/en/built-in-function-reference.html .

Guess you like

Origin blog.csdn.net/atwdy/article/details/127010700