使用PHP和MySQL。在我的表中,有NOW()sql函数记录的日期字段(日期时间)。此字段中数据的示例值为2010-10-07 10:57:36。如何选择今天的每月 - 每年的所有数据。我尝试使用如下代码:
SELECT * FROM table WHERE date=????
SELECT * FROM table where DATE(date)=CURDATE()
试试这个:
SELECT * FROM table WHERE date > CURDATE();
CURDATE()
将当前日期作为2011-10-07
返回,当将2011-10-07 00:00:00
s与它进行比较时将投射到datetime
。
请注意,如果您使用DATE(date) = CURDATE()
,您将为表中的每一行运行日期转换,如果您有许多行和/或您需要经常运行查询,这将对您的性能非常不利。还要确保你在date
上有一个索引,否则两种方法都会更慢。
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');
等等。
试试这个
SELECT * FROM table WHERE DATE(my_date)=DATE(now())
my_date -> column name
SET @day = '2017-12-12' ;
SELECT * FROM table WHERE dateColumn BETWEEN DATE(@day) AND DATE_ADD(DATE(@day), INTERVAL 1 DAY ) ;
使用这样的东西它完全适用于我的代码(访问数据库):
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';