我有一个类型为“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
然而,这将返回一个空结果集。有什么建议吗?
使用WHERE DATE(datetime) = '2009-10-20'存在性能问题。如下所述:
它将为所有行计算DATE(),包括那些不匹配的行。
这将使查询不可能使用索引。
使用允许使用索引的BETWEEN或>,<,=操作符:
SELECT * FROM data
WHERE datetime BETWEEN '2009-10-20 00:00:00' AND '2009-10-20 23:59:59'
更新:在索引列中使用LIKE而不是操作符的影响很大。下面是一个包含1,176,000行的表的一些测试结果:
使用datetime LIKE '2009-10-20%' => 2931毫秒
using datetime >= '2009-10-20 00:00:00' AND datetime <= '2009-10-20 23:59:59' => 168ms
当对同一个查询执行第二次调用时,差异甚至更大:2984ms vs 7ms(是的,只有7毫秒!)我是在用Hibernate重写一个项目的一些旧代码时发现的。
你可以使用:
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))
这里是所有的格式
假设这是包含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 |
+----------------------+