【问题标题】:Check the year of timestamps [duplicate]检查时间戳的年份[重复]
【发布时间】:2019-11-14 22:50:08
【问题描述】:

我已经在我的数据库中存储了时间戳。 483753600799286400等时间戳。

我想检查 2015 年是否与我的任何时间戳匹配。

我知道我能做到的唯一方法是从数据库中获取 ALL 时间戳,然后使用 getdate(799286400)['year'] 检查每个时间戳的年份。这将是一个解决方案,但它对性能来说太糟糕了!有没有其他更温和的方法来做到这一点?

更新

这是我迄今为止尝试过的:

public function dateOfBirth(string $year): array {
    return $query = $this->createQueryBuilder('p')
            ->select('p.uid')
            ->where("p.dateOfBirth BETWEEN :start AND :end")
            ->setParameter('start', "$year-01-01")
            ->setParameter('end', "$year-01-01")
            ->getQuery()
            ->getResult();
}

但它返回一个空数组。

【问题讨论】:

标签: php mysql sql symfony doctrine-orm


【解决方案1】:

看起来您正在存储纪元时间戳。要检查属于 2015 年的时间戳,一种有效的方法是生成表示年份边界的纪元时间戳范围,然后将其与存储的值进行比较。假设时间戳存储在col列中:

select exists (
    select 1
    from mytable    
    where col >= unix_timestamp('2015-01-01') and col < unix_timestamp('2016-01-01')
) as exists_year_2015

此查询将为您提供一条唯一记录,其中包含一个布尔值 (0/1) 的唯一列,该值指示表中的任何记录是否具有属于 2015 年的时间戳。

这样的表达式将能够利用时间戳列上的索引。

【讨论】:

  • 谢谢,但能否请您告诉我如何使用 Symfony 做同样的事情?我已经更新了我的问题。
【解决方案2】:

你的代码有几个问题,首先你要返回一个作业

return $query = $this->createQue...

您还为:start:end 设置了相同的参数值,字符串"$year-01-01" 与存储的时间戳不匹配,并且您不会在两者之间更改$year 的值,即使它可以匹配它将是一个空范围。

您需要确定给定年份的开始和结束时间戳,并将它们用作查询的参数。

public function dateOfBirth(string $year): array {
    // get the DateTimes
    $startDate = new \DateTime("midnight January 1, $year");
    $year += 1;
    $endDate = new \DateTime("midnight January 1, $year");
    // get the timestamps
    $start = $startDate->format('U');
    $end = $endDate->format('U');

    return $this->createQueryBuilder('p')
            ->select('p.uid')
            ->where("p.dateOfBirth > :start")
            ->andWhere("p.dateOfBirth < :end")
            ->setParameter('start', $start)
            ->setParameter('end', $end)
            ->getQuery()
            ->getResult();
}

【讨论】:

  • 很好的答案!这对我帮助很大。非常感谢!
猜你喜欢
  • 2015-07-17
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多