【问题标题】:MySQL - Using a date range vs functionsMySQL - 使用日期范围与函数
【发布时间】:2013-08-11 16:38:03
【问题描述】:

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

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

结果:1​​5,982

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

结果:1​​6,278

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

谢谢。

【问题讨论】:

  • created_at 列的类型是什么?如果它碰巧是基于字符的列而不是日期列,则可能无法按预期进行比较。

标签: mysql date date-range


【解决方案1】:

两个查询应该是等效的,除了第一个能够使用索引并且应该更快,并且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 将不包含在内。

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 2019-02-10
      相关资源
      最近更新 更多