0

我需要知道 6 月和 7 月有多少用户注册,这是我写的第一个查询:

select count(*) from users where created_at>="2013-06-01" and created_at<="2013-07-31"

结果:15,982

select count(*) from users where year(created_at)=2013 and month(created_at) in (6,7)

结果:16,278

为什么他们返回不同的结果?有人可以解释一下吗?还是我错过了什么?

谢谢。

4

2 回答 2

2

两个查询应该是等效的,除了第一个能够使用索引并且它应该更快,并且除了created_at不是 DATE 而是 TIMESTAMP 的情况。

如果created_at是一个时间戳,你应该这样写你的第一个查询:

select count(*) from users
where created_at>='2013-06-01' and created_at<'2013-08-01'

否则,您的第一个查询将排除在 7 月 31 日午夜之后创建的所有记录,例如。2013-07-31 00:00:00将包括在内,而2013-07-31 09:15:43不会。

于 2013-08-09T17:03:36.530 回答
1

原因是您的日期值不包括最后一天:日期常量在午夜转换为时间戳。您正在这些值之间进行查询:

2013-06-01 00:00:00
2013-07-31 00:00:00

所以只包括最后一天的第一秒。

尝试这个:

select count(*)
from users
where created_at>="2013-06-01"
and created_at<="2013-07-31 23:59:59"

或者更简单地说,少于第二天

select count(*)
from users
where created_at>="2013-06-01"
and created_at<"2013-08-01" -- < 1st day of next month
于 2013-08-09T17:05:48.587 回答