使用PHP和MySQL。在我的表中,有一个日期字段(datetime),由NOW()SQL函数记录。该字段中的数据示例值为2010-10-07 10:57:36。如何选择今天的所有日期月年数据。我尝试使用以下代码:
SELECT * FROM table WHERE date=????
尝试这样:
SELECT * FROM table WHERE date > CURDATE();
CURDATE()
函数返回的是当前日期,格式为2011-10-07
,但是在与datetime
进行比较时会被强制转换为2011-10-07 00:00:00
。
需要注意的是,如果你使用DATE(date) = CURDATE()
语句,那么每行数据都要进行一次日期转换,如果表中有很多行并且需要频繁查询,这将导致查询效率极低。同时,确保对date
字段建立索引,否则两种方法都会变得更加缓慢。
SELECT * FROM table where DATE(date)=CURDATE()
SELECT * FROM tableName WHERE DATE(fieldDate) = DATE(NOW());
date_format
函数允许您轻松切换不同的粒度:
选择与同一天相同的所有内容:
select * from table
where date_format(date, '%Y-%m-%d') = date_format(now(), '%Y-%m-%d');
同月:
select * from table
where date_format(date, '%Y-%m') = date_format(now(), '%Y-%m');
同年:
select * from table
where date_format(date, '%Y') = date_format(now(), '%Y');
从同一时间开始:
select * from table
where date_format(date, '%Y-%m-%d %H') = date_format(now(), '%Y-%m-%d %H');
等等。
SET @day = '2017-12-12' ;
SELECT * FROM table WHERE dateColumn BETWEEN DATE(@day) AND DATE_ADD(DATE(@day), INTERVAL 1 DAY ) ;
试试这个
SELECT * FROM table WHERE DATE(my_date)=DATE(now())
my_date -> column name
使用类似这样的代码,它在我的代码中完美运行(访问数据库):
select * from Table t where t.column>=Date() and t.column< Date() + 1
使用之间。
select * from table date between '2010-10-06' and '2010-10-08';
GETDATE()
。 - Kaivosukeltaja