我有一个类型为“datetime”的列,其值如2009-10-20 10:00:00

我想从datetime中提取date并写一个查询:

SELECT * FROM 
data 
WHERE datetime = '2009-10-20' 
ORDER BY datetime DESC

以下是最好的方法吗?

SELECT * FROM 
data 
WHERE datetime BETWEEN('2009-10-20 00:00:00' AND '2009-10-20 23:59:59')
ORDER BY datetime DESC

然而,这将返回一个空结果集。有什么建议吗?


当前回答

这里是所有的格式

假设这是包含datetime值的列,表数据。

+--------------------+
| date_created       |
+--------------------+
| 2018-06-02 15:50:30|
+--------------------+

mysql> select DATE(date_created) from data;
+--------------------+
| DATE(date_created) |
+--------------------+
| 2018-06-02         |
+--------------------+

mysql> select YEAR(date_created) from data;
+--------------------+
| YEAR(date_created) |
+--------------------+
|               2018 |
+--------------------+

mysql> select MONTH(date_created) from data;
+---------------------+
| MONTH(date_created) |
+---------------------+
|                   6 |
+---------------------+

mysql> select DAY(date_created) from data;
+-------------------+
| DAY(date_created) |
+-------------------+
|                 2 |
+-------------------+

mysql> select HOUR(date_created) from data;
+--------------------+
| HOUR(date_created) |
+--------------------+
|                 15 |
+--------------------+

mysql> select MINUTE(date_created) from data;
+----------------------+
| MINUTE(date_created) |
+----------------------+
|                   50 |
+----------------------+

mysql> select SECOND(date_created) from data;
+----------------------+
| SECOND(date_created) |
+----------------------+
|                   31 |
+----------------------+

其他回答

你可以使用MySQL的DATE()函数:

WHERE DATE(datetime) = '2009-10-20'

你也可以试试这个:

哪里的日期时间像“2009-10-20%”

有关使用LIKE的性能影响的信息,请参阅这个答案。

你可以使用:

DATEDIFF ( day , startdate , enddate ) = 0

或者:

DATEPART( day, startdate ) = DATEPART(day, enddate)
AND 
DATEPART( month, startdate ) = DATEPART(month, enddate)
AND
DATEPART( year, startdate ) = DATEPART(year, enddate)

Or:

CONVERT(DATETIME,CONVERT(VARCHAR(12), startdate, 105)) = CONVERT(DATETIME,CONVERT(VARCHAR(12), enddate, 105))

在语句中使用LIKE是最好的选择 哪里的日期时间像“2009-10-20%” 在这种情况下应该是成立的

您可以将datetime格式化为Y-M-D部分:

DATE_FORMAT(datetime, '%Y-%m-%d')

简单和最好的方式使用日期函数

例子

SELECT * FROM 
data 
WHERE date(datetime) = '2009-10-20' 

OR

SELECT * FROM 
data 
WHERE date(datetime ) >=   '2009-10-20'  && date(datetime )  <= '2009-10-20'