当前位置:网站首页>One article quick learning - playing with MySQL time operation function and detailed explanation of time matching operation + instance code
One article quick learning - playing with MySQL time operation function and detailed explanation of time matching operation + instance code
2022-06-21 11:15:00 【fanstuck】
Catalog
9.to_days(date),from_days(days)
Focus , Prevent losing , If there is a mistake , Please leave a message , Thank you very much
Preface
Time is often used as a time index in a database , Changes are required during data warehousing, outbound and update . When calculating some indicators or extracting data for a certain period of time , Will operate according to the time index data in the database . Therefore, a large part of our operation data must start from the time data , But we want to really extract the time we want as an index , We also need to master many functions to facilitate our operation , This is a complicated application process .
In my blog database MySQL Three articles have explained in detail most of the functions for processing time data and the application of examples , If you have a need in this respect, you can read these three articles :
One text speed learning - Get along well with MySQL Acquisition time 、 Detailed explanation of various operation methods for format conversion
The first chapter details all the acquisition SQL A function of local time , And the conversion of other data types to time data types .
The second chapter details all MySQL Time data selects a function that specifies the time .
The third chapter deals with time variables interval The use and relevance of interval Usage of partition function . These three articles basically cover MySQL Time data processing and all functions obtained , Now only the time operation function and related functions are left to be explained . The above three chapters are all basic parts , And there are relevant example code displays . This blog will further explain the implementation of more complex time combination operation functions .
I hope I can help you who are reading this blog , If there are any problems that can not be solved, please put forward them in the comment area , Bloggers will answer one by one . Let's start with the text .
The database and tables shown above are still the same value_test form :

The fields used are generally time as well as create_time, among time In order to bigint Form storage of , and create_time In order to datetime Time type data storage .
One 、 Time plus minus
1. Time variable operation
The foregoing also describes in detail about interval How to use this keyword , Generally, it is the operation of time :
For example, subtracting one day's time is :
select (create_time - interval 1 day ) as times from value_test
I don't want to repeat it here , If you want to know more, you can go to the third article .
2.date_add()
date_add As the name suggests, it means to add a time interval , Basic grammar :
date_add(< Time data >,interval < The number > < Time unit > )The following time units and interval The type of time unit is the same , The suffix time unit has also been mentioned in the third article , There's no demo here , Here are some more complex time values based on the articles in the first three pages :
Select the data in the total time slice from the beginning to the last seven days :
between cast(date_sub(date_format(curdate(),'%Y%m%d') , interval 7 day)
as DECIMAL)
and cast(date_sub(date_format(curdate(),'%Y%m%d') , interval 1 day)
as DECIMAL)Select yesterday's data :
and time= cast(date_sub(date_format(curdate(),'%Y%m%d') , interval 1 day)
as DECIMAL)After reading the first three articles, you should have a good understanding of the functions of applying these functions , You can add and subtract time at will .
3. date_sub()
Subtract one time interval , Here you can use interval Many time units to achieve some precise time operations .
select date_sub(create_time ,interval '1 10:10:10' day_second )
as times from value_test
Means to subtract 1 God 1 Hours 10 minute 10 second :

You can also use date_add() Instead of , as long as interval A negative number is good . Such as :
select date_add(create_time ,interval '-1 10:10:10' day_second )
as times from value_test

4.period_add()
period_add() The basic syntax format of the function is :
period_add(P,N)from add You can see that it is also an additive function ,P For the specified number of dates , and N Is the time of addition and subtraction . and date_add The difference is ,period_add No need to use interval Specify the date value , This function is based on the input P Automatically determine the unit of addition and subtraction . When the input is yyyymm when ,N It is judged as the sum of months :
select PERIOD_ADD(202201,10) as times

When the input is yyyymmdd when ,N Determined as days :
select PERIOD_ADD(20220101,10) as times

When using this function, you should pay attention to ,period_add Does not apply to column operations , If it is used for a column for operation, an error will be reported :
select PERIOD_ADD(time,10) as times from value_test
> Incorrect arguments to period_add
5.period_diff(P1,P2)
This function returns P1-P2 The time difference ,P1 and P2 It has to be for yyyymm The form of month and year , To tell you the truth, this function is almost useless , Very chicken ribs .
select PERIOD_diff(202201,202202)as times 
6.datediff(date1,date2)
Returns the interval between two dates :
select datediff('20220601','20220501') as time ![]()
however date1 and date2 Can only be date yyyymmdd, Not in this format will be output null.
This function can not only identify time type data , It can also work with other types of stored time data :
select datediff(time,'20220501') as time from value_test 
And as soon as they arrive yyyymmdd This format can be used to calculate :
select datediff(create_time,'20220501') as time from value_test
7.timediff(time1,time2)
Format and above datediff equally , It doesn't have any features :
select timediff(time(create_time),'01:00:00') as time from value_test 
8.time_to_sec()、sec_to_time()
time_to_sec() This function can convert all the time into seconds :
select time_to_sec(time(create_time)) as time from value_test 
sec_to_time() This function converts seconds into time , and time_to_sec() The other way around , You can stack it again and go back to the original function :
select sec_to_time(time_to_sec(time(create_time))) as time from value_test
9.to_days(date),from_days(days)
to_days() Input date Date converted to days :
select to_days(time) as time from value_test
date The input parameter does not specify that time type data is required , Other time type formats that can be recognized by storage can be .
Its termination time is :0000/00/00
from_days() On the contrary , Convert days to date, Here we also use two nesting to get the original data :
select from_days(to_days(time)) as time from value_test 
10.time_formate
Here we make up for the omission of the time conversion function in the previous article time_format function , The usage is simple and limited to time time, And date_format The difference is :time_format Time can be converted into 00.00.00 In the form of :
select time_format(time(create_time),'%H.%i.%s') as time from value_test 
Two 、 Time format matching
1.get_format()
get_format() Function syntax format is :
get_format(< Time data >,'< Specify the characters 'eur'|'usa'|'jis'|'iso'|'internal'>')select GET_FORMAT(date,'usa' ) as time 
Here, it is directly posted in the form of charts :
| Time type | Regional time format | Return results |
| date | 'usa' | '%m.%d.%Y' |
| date | 'jis' | '%Y-%m-%d' |
| date | 'iso' | '%Y-%m-%d' |
| date | 'eur' | '%d.%m.%Y' |
| date | 'internal' | %Y%m%d' |
| datetime | 'usa' | '%Y-%m-%d %H.%i.%s' |
| datetime | 'jis' | '%Y-%m-%d %H:%i:%s' |
| datetime | 'iso' | '%Y-%m-%d %H:%i:%s' |
| datetime | 'eur' | '%Y-%m-%d %H.%i.%s' |
| datetime | 'internal' | '%Y%m%d%H%i%s' |
| time | 'usa' | '%h:%i:%s %p' |
| time | 'jis' | '%H:%i:%s' |
| time | 'iso' | '%H:%i:%s' |
| time | 'eur' | '%H.%i.%s' |
| time | 'internal' | %H%i%s' |
2.substr()
Basic grammar :
substr(string string,num start,num length);- string: by character string ;
- start: Is the starting position ;
- length: For the length .
If we want to select the date of the current month :
and substr(time,1,6) = substr( cast(date_sub(date_format(curdate(),'%Y%m%d')
, interval 1 day) as DECIMAL),1,6)
Cannot start from 0 Start , Only from 1 Start .
select time from value_test
WHERE substr(time,1,6)>'202205'
and substr(time,1,6)<'202207'So you can choose 6 All the data of the month .
Focus , Prevent losing , If there is a mistake , Please leave a message , Thank you very much
That's what this issue is all about . I am a fanstuck , If you have any questions, please leave a message for discussion , See you next time .
Refer to the :mysql Time function
边栏推荐
- MySQL advanced - personal notes
- How to learn function test? Ali engineer teaches 4 steps
- 《Feature-metric Loss for Self-supervised Learning of Depth and Egomotion》论文笔记
- Solon 1.8.3 release, cloud native microservice development framework
- Flynk CDC reads MySQL 8 hours late. Set the servertimezone parameter
- 轻量级开源SAST工具semgrep分析1/2
- map.values()转为List和ArrayList的复制
- Citus 11 for Postgres 完全开源,可从任何节点查询(Citus 官方博客)
- is not allowed to connect to this mysql server
- Prometheus flask exporter usage example
猜你喜欢
随机推荐
numpy | 插入不定长字符数组测试OK
MySQL - data type
Quickly analyze oom using mat tools
【100个 Unity踩坑小知识点】| Unity 使用Quaternion.AngleAxis随机一个方向
一文速学-玩转MySQL时间运算函数以及时间匹配操作详解+实例代码
IMU选型、标定误差分析、AHRS组合导航
There are obvious signs of oversupply of chips, ASML is no longer a pastry, and investment institutions are shorting on a large scale
文旅新体验!3DCAT助力广州非遗“元宇宙”街区炫酷亮相
《Feature-metric Loss for Self-supervised Learning of Depth and Egomotion》论文笔记
C语言初阶(七)结构体
Do you understand the capacity expansion mechanism of ArrayList?
Kotlin - I/O流
Yum source server configuration
C# Cannot access child value on Newtonsoft.Json.Linq.JProperty
为什么 C# 访问 null 字段会抛异常?
Redis core: usage specification
告别无尽盛夏
【100个 Unity踩坑小知识点】| 在编辑器中绘制正方体虚线、球体虚线(Gizmos 辅助线框)
启牛到底是用的什么证券开户?开户是哪家的安全吗
Detailed explanation of connection pool parameter settings (view while adjusting)









