MySQL如何从今天记录的表中选择数据?

问题描述 投票:15回答:8

使用PHP和MySQL。在我的表中,有NOW()sql函数记录的日期字段(日期时间)。此字段中数据的示例值为2010-10-07 10:57:36。如何选择今天的每月 - 每年的所有数据。我尝试使用如下代码:

  SELECT * FROM table WHERE date=????
php mysql datetime select
8个回答
22
投票

SELECT * FROM table where DATE(date)=CURDATE()


27
投票

试试这个:

SELECT * FROM table WHERE date > CURDATE();

CURDATE()将当前日期作为2011-10-07返回,当将2011-10-07 00:00:00s与它进行比较时将投射到datetime

请注意,如果您使用DATE(date) = CURDATE(),您将为表中的每一行运行日期转换,如果您有许多行和/或您需要经常运行查询,这将对您的性能非常不利。还要确保你在date上有一个索引,否则两种方法都会更慢。


3
投票
SELECT * FROM tableName WHERE DATE(fieldDate) = DATE(NOW());

2
投票

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');

等等。


1
投票

试试这个

SELECT * FROM table WHERE DATE(my_date)=DATE(now())

my_date -> column name

1
投票
SET @day = '2017-12-12' ;

SELECT * FROM table WHERE dateColumn BETWEEN DATE(@day) AND DATE_ADD(DATE(@day), INTERVAL 1 DAY ) ;

0
投票

使用这样的东西它完全适用于我的代码(访问数据库):

select * from Table t where t.column>=Date() and t.column< Date() + 1

-2
投票

之间使用。

select * from table date between '2010-10-06' and '2010-10-08';
© www.soinside.com 2019 - 2024. All rights reserved.