更好的是:选择截断日期或之间的日期

时间:2014-05-14 14:53:37

标签: mysql

我需要创建一个查询来根据日期选择我的mysql数据库的一些数据,但在我的where子句中我必须选择:

1 - 截断日期:

select count(*) from mailing_user where date_format(create_date, '%Y-%m-%d')='2013-11-05';

2 - 在

之间使用
select count(*) from mailing_user where create_date between '2013-11-05 00:00:00' and '2013-11-05 23:59:59';

这两个查询会起作用,但哪个更好?或者,推荐什么?为什么呢?

3 个答案:

答案 0 :(得分:1)

这是一篇要阅读的文章。

http://willem.stuursma.name/2009/01/09/mysql-performance-with-date-functions/

如果您的created_date列已建立索引,则第二个查询将更快。

但是如果列没有编入索引,并且这是您定义的日期格式,则可以使用以下查询。

select count(*) from mailing_user where DATE(create_date) = '2013-11-05';

我使用DATE代替DATE_FORMAT,因为我可以使用以此格式获取的原生功能('2013-11-05')。

答案 1 :(得分:1)

根据documentation A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision.

,根据您的问题,您似乎想要从一天中选择记录

所以这意味着你的第二个查询可能实际上运气不好并错过了当天最后一秒插入表中的一些记录,所以我想说第一个更精确并保证总是得到正确的结果。

这样做的缺点是你无法使用date_format - 函数索引该列,因为MySQL并不是很酷。

如果您不想使用date_format并解决精确问题,则可以更改

where create_date between '2013-11-05 00:00:00' and '2013-11-05 23:59:59'

where create_date >= '2013-11-05 00:00:00' and create_date < '2013-12-05 00:00:00'

答案 2 :(得分:0)

如果你在create_date上有一个索引,那么第二个会更快,因为第一个人不能使用索引来快速扫描结果。
但是,这需要在create_date上有一个索引。

否则我想他们会有类似的速度,可能第二个仍然会更快,因为比较的处理时间较短(日期时间比较而不是转换为字符串和比较字符串),但我怀疑它是否是显著。

相关问题