Use time query in Mysql

1. Use the equal sign to query

You can use the equal sign to query like a normal query, but the query time must be exactly equal to the corresponding time of the field. For example, I want to check the following value

insert image description here
The sql is as follows:

SELECT id, start_time, end_time FROM pay_fee_rule WHERE start_time ='2022-10-9 10:33:39' 

search result:

insert image description here

But as long as one of the values ​​is changed, it will not be found out. For example, if the value is changed to "2022-10-9 10:33:38", the query results are as follows:

insert image description here
Time generally does not use "=" query.

2. Query a certain month, a certain day, a certain year

If I want to query all the data in October 2022, I can use DATE_FORMAT (field name, '%Y-%m') = DATE_FORMAT ('query time field', '%Y-%m'), the sql is as follows:

SELECT id, start_time, end_time FROM pay_fee_rule WHERE DATE_FORMAT(start_time, '%Y-%m') = DATE_FORMAT('2022-10-9 10:33:38', '%Y-%m')

The query results are as follows:

insert image description here
To query a certain day, such as querying the data on October 11, 2022, you can use DATE_FORMAT('query time field', '%Y-%m-%d'), the sql is as follows:

SELECT id, start_time, end_time FROM pay_fee_rule WHERE DATE_FORMAT(start_time, '%Y-%m-%d') = DATE_FORMAT('2022-10-11 10:33:38', '%Y-%m-%d')

The result is as follows:

insert image description here

What about querying a certain year? For example, to query data in 2021, use DATE_FORMAT('query time field', '%Y'), the sql is as follows:

SELECT id, start_time, end_time FROM pay_fee_rule WHERE DATE_FORMAT(start_time, '%Y') = DATE_FORMAT('2021-10-9 10:33:38', '%Y')

The result is as follows:
insert image description here

3. Query time range

For example, I want to query all the data from September to February 22, use DATE_FORMAT with ">=" and "<=", the sql is as follows:

SELECT id, start_time, end_time FROM pay_fee_rule WHERE DATE_FORMAT(start_time, '%Y-%m') >= DATE_FORMAT('2022-10-9 10:33:38', '%Y-%m') AND DATE_FORMAT(start_time, '%Y-%m') <= DATE_FORMAT('2022-12-9 10:33:38', '%Y-%m') ORDER BY start_time

The result is as follows:

insert image description here
To query the data before October 11, 22, the sql is as follows:

SELECT id, start_time, end_time FROM pay_fee_rule WHERE DATE_FORMAT(start_time, '%Y-%m-%d') < DATE_FORMAT('2022-10-11 10:33:38', '%Y-%m-%d') ORDER BY start_time

The result is as follows:

insert image description here

It is not difficult to query the time, as long as you know whether to use the year, month or day, and write the correct characters to format the time.

Guess you like

Origin blog.csdn.net/studio_1/article/details/127381621