MySql query time period method (transfer)

Reference: http://www.jb51.net/article/58668.htm

 

MySql's time fields include date, time, datetime, timestamp, etc. Often when we store data, we store the entire time in one field, using the datetime type; it may also be used to separate date and time, that is, one field stores date, and one field stores date. Storage time time. No matter how it is stored, in practical applications, there are likely to be queries that include a "time period" type, such as an access record database, which needs to count the number of visits per day, and each day is a time period. The following introduces two common methods of MySql query time period, and other databases can also be implemented similarly.

Method 1: The traditional method , that is, specify the start time and end time, and use "between" or "<", ">" to establish conditions, such as querying the number of data items from March 1, 2010 to March 2, 2010, then you can use

 code show as below:
SELECT
	count(*)
FROM
	subjectable
WHERE
	datetimecolumn >= '2010-03-01 00:00:00'
AND datetimecolumn < '2010-03-02 00:00:00'
 

 

However, this method is less efficient in comparison because the time is not an integer data, so if the amount of data is large, the time can be converted into an integer UNIX timestamp, which is the second method.

Method 2: UNIX timestamp , each time corresponds to a unique UNIX timestamp, which starts from '1970-01-01 00:00:00' as 0 and increases by 1 every second. MySql has built-in traditional time and UNIX time interchange functions, which are:

UNIX_TIMESTAMP(datetime)
FROM_UNIXTIME(unixtime)

such as running

code show as below:
SELECT
	UNIX_TIMESTAMP('2010-03-01 00:00:00')
 

 

return 1267372800

run

code show as below:
SELECT
	FROM_UNIXTIME(1267372800)
 

 

returns '2010-03-01 00:00:00'

Therefore, we can replace the data in the time field with the integer UNIX time, so that the comparison time becomes an integer comparison, and the efficiency can be greatly improved after the index is established. When querying, you need to convert the start time and end time to UNIX time and compare them, such as:

code show as below:
SELECT
	count(*)
FROM
	subjectable
WHERE
	datetimecolumn >= UNIX_TIMESTAMP('2010-03-01 00:00:00')
AND datetimecolumn < UNIX_TIMESTAMP('2010-03-02 00:00:00')
 

 

It can also be converted to UNIX time in the calling program and then passed to MySql. In short, this method is conducive to fast query time period, but the display time needs to be reversed again.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326830738&siteId=291194637