Mysql query in DATE_SUB use in conjunction with examples to explain the information

Often query for the specified time or time period when the data query or menu, for example, to query information within a day, within a week to query information, to inquire, network engineers within the company this month to introduce DATE_SUB function, combined with examples to explain, we hope to help new colleagues. 

Definition and Usage

DATE_SUB () function interval from date minus a specified time.

1. Grammar

DATE_SUB(date,INTERVAL expr type)
date  parameter is valid date expression. expr  parameter is the time interval you want to add.
type parameter can be the following values:
Type Value
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
SECOND_MICROSECOND
MINUTE_MICROSECOND
MINUTE_SECOND
HOUR_MICROSECOND
HOUR_SECOND
HOUR_MINUTE
DAY_MICROSECOND
DAY_SECOND
DAY_MINUTE
DAY_HOUR
YEAR_MONTH

Simple examples

Suppose we have the following table:
OrderId ProductName OrderDate
1 'Computer' 2012-12-29 16:25:46.635
Now we want from the "OrderDate" minus two days.
We use the following SELECT statement:
SELECT OrderId,DATE_SUB(OrderDate,INTERVAL 2 DAY) AS OrderPayDate  FROM Orders  
result:
OrderId OrderPayDate
1 2012-12-27 16:25:46.635
3.复杂实例:

查询一天:
    select * from table where to_days(column_time) = to_days(now());
    select * from table where date(column_time) = curdate(); 
查询一周:
    select * from table where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(column_time);
查询一个月:
    select * from table where DATE_SUB(CURDATE(), INTERVAL 1 MONTH) <= date(column_time);
查询指定天数
    select * from table where DATE_SUB(CURDATE(), INTERVAL 2 DAY) <= date(column_time);
 
From the article: Nanchang Could Media Reprinted from: http://www.mofeimedia.com

Guess you like

Origin www.cnblogs.com/ncncnc/p/12144123.html