MySQL使用DATETIME字段中的DATE返回今天的记录

时间:2022-09-16 14:30:30

I have a table called "actions" with a DATETIME column called "occurred". I'm trying to return the records for today by doing the following

我有一个名为“actions”的表,其中有一个名为“occurrence”的DATETIME列。我正在尝试通过执行以下操作返回今天的记录

SELECT * FROM `actions` WHERE `occurred` = DATE(NOW());

But I get an empty result set. If I take the WHERE clause out, I can see all 295 rows in the table and there's at least 30 rows from today. Later I will be writing another query to return all records between today's date and X amount of days in the past but before I can get there I need to know why this query is returning an empty result set.

但我得到一个空的结果集。如果我取出WHERE子句,我可以看到表中的所有295行,并且从今天开始至少有30行。稍后我将编写另一个查询来返回今天的日期和过去的X天数之间的所有记录,但在我到达那里之前,我需要知道为什么这个查询返回一个空的结果集。

Thanks in advance.

提前致谢。

2 个解决方案

#1


4  

If there in no future date in occurred, you could just use below:

如果未来的日期没有发生,您可以在下面使用:

SELECT * FROM `actions` WHERE `occurred` > DATE_SUB(CURDATE(), INTERVAL 1 DAY);

#2


7  

SELECT * FROM actions WHERE DATE(ocurred) = CURDATE();

DATE(ocurred) ignores the time part.

DATE(ocurred)忽略了时间部分。

Here's the SQL Fiddle to play with the data: http://www.sqlfiddle.com/#!2/81708/2

以下是使用数据的SQL小提琴:http://www.sqlfiddle.com/#!2/81708/2

#1


4  

If there in no future date in occurred, you could just use below:

如果未来的日期没有发生,您可以在下面使用:

SELECT * FROM `actions` WHERE `occurred` > DATE_SUB(CURDATE(), INTERVAL 1 DAY);

#2


7  

SELECT * FROM actions WHERE DATE(ocurred) = CURDATE();

DATE(ocurred) ignores the time part.

DATE(ocurred)忽略了时间部分。

Here's the SQL Fiddle to play with the data: http://www.sqlfiddle.com/#!2/81708/2

以下是使用数据的SQL小提琴:http://www.sqlfiddle.com/#!2/81708/2