MYSQL implements date and time range retrieval, date and time query, date and time function operation query, query of data in a time period, query of data cases several years ago or within a few years

In mysql, you can format the date and time, and you can also query according to the date and time range. Today I have summarized several commonly used range query cases, and then share it here:

如下例子中我会使用yyyy-MM-dd的日期格式,其他格式只要保证过滤条件的时间格式和数据库中的格式一致即可
Filter query by time:
This example is to query the data before 2023/4/18, where the comparison operator can be replaced as required.

SELECT
	* 
FROM
	table_name 
WHERE
	time_field < '2023/4/18';

Filter the query according to the time range:
This example is to query the data from 2023/4/18 to the present, and the CURDATE() function is used to obtain the current date.

SELECT
	* 
FROM
	table_name 
WHERE
	time_field BETWEEN '2023/4/18' 
	AND CURDATE();

Filter query according to time (date time function operation):
This example is to query data from one year ago;
the DATE_SUB() function is used to subtract one year from the current date to get the date one year ago from the current time, and finally pass The WHERE clause filters out the data that meets the condition.

SELECT
	* 
FROM
	my_table 
WHERE
	my_time_field <= DATE_SUB( CURDATE(), INTERVAL 1 YEAR );

Filter the query according to the time range (date time function operation):
this example is to query the data from the current date to the time
of next year; the DATE_ADD() function is used to add one year to the current date to get the date one year after the current time date, and finally filter out the data that meets the conditions through the WHERE clause.

SELECT
	* 
FROM
	table_name 
WHERE
	time_field BETWEEN CURDATE() 
	AND DATE_ADD( CURDATE(), INTERVAL 1 YEAR );

Guess you like

Origin blog.csdn.net/TangBoBoa/article/details/130228935