MySQL查询:使用日期时间函数(mysql日期查询)

Nowadays, people use MySQL to store data in the computing world. So it’s important to learn some basic knowledge about SQL query. This article focuses on knowning how to use MySQL date and time functions when writing a query.

When we need to make a comparison between two dates and use a certain syntax, we can use the Date/Time function. They are `DATE()`, `DATE_ADD()`,`DATE_SUB()` and `CURDATE()`.

First of all, to get the date for part of the query, we can use `DATE()` function. This function takes a string and returns a date value in the form of YYYY-MM-DD, for example `SELECT DATE(‘2016-12-25’)`, the results will be ‘2016-12-25’.

If we need to calculate future date or past date from an existing date, we can use the `DATE_ADD()` and `DATE_SUB()` functions. For example, `SELECT DATE_ADD(CURDATE(),INTERVAL 3 DAY)`, in this query, we add three days to today’s date and the result will be three days after today’s date.

Meanwhile, `DATE_SUB()` is used to get the result which is before the existing date. For example `SELECT DATE_SUB(CURDATE(), INTERVAL 7 DAY)`, the result will be one week prior to today’s date.

At last, `CURDATE()` is a very useful and frequently used date function. It returns the current date in the form of YYYY-MM-DD, for example `SELECT CURDATE()`, the result will be today’s date with the time stamp along with it.

In conclusion, MySQL date and time functions are very useful in writing queries. We can use it to make comparisons between two dates, and also get future or past dates with evey ease and accuracy.


数据运维技术 » MySQL查询:使用日期时间函数(mysql日期查询)