(转载)http://blog.163.com/dreamman_yx/blog/static/26526894201053115622827/
查询
今天
select * from 表名 where to_days(时间字段名) = to_days(now());
昨天
SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ) - TO_DAYS( 时间字段名) <= 1
7天
SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(时间字段名)
近30天
SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(时间字段名)
本月
SELECT * FROM 表名 WHERE DATE_FORMAT( 时间字段名, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )
上一月
SELECT * FROM 表名 WHERE PERIOD_DIFF( date_format( now( ) , '%Y%m' ) , date_format( 时间字段名, '%Y%m' ) ) =1
例子1:
mysql> select time('2013-05-13 19:50:33'); +-----------------------------+ | time('2013-05-13 19:50:33') | +-----------------------------+ | 19:50:33 | +-----------------------------+ 1 row in set (0.05 sec) mysql> select date('2013-05-13 19:50:33'); +-----------------------------+ | date('2013-05-13 19:50:33') | +-----------------------------+ | 2013-05-13 | +-----------------------------+ 1 row in set (0.00 sec)
例子2:
mysql> select to_days(now()); +----------------+ | to_days(now()) | +----------------+ | 735425 | +----------------+ 1 row in set (0.03 sec) mysql> select to_days('2013-07-07 19:30:30'); +--------------------------------+ | to_days('2013-07-07 19:30:30') | +--------------------------------+ | 735421 | +--------------------------------+ 1 row in set (0.00 sec) mysql>