【问题标题】:PHP Postgres query using timestamp interval使用时间戳间隔的 PHP Postgres 查询
【发布时间】:2014-08-21 08:57:55
【问题描述】:

我正在尝试使用 2 个时间戳运行查询。我不确定如何在“到”时间戳中添加一天。我想添加一天,因此将包括 03-31 的 23:59。如果有更好的方法来进行这种包容性搜索,请随时告诉我。

$from = "2014-01-01";
$to = "2014-03-31";

pg_prepare($db, 'my_query'
        , "select * from table where from >= $1 and to < $2 + interval '1' day");

$results = pg_execute($db,'my_query',array($from, $to));

【问题讨论】:

  • where foo between '2014-01-01' and '2014-03-31' 是您所需要的。 between 包含在内,可以重写为where foo &gt;= '2014-01-01' AND foo &lt;= '2014-03-31'
  • 这是否包括'2014-03-31 00:00:01' and '2014-03-31 23:59:59'之间的时间
  • where foo:date,如果是日期时间字段?如果您只对日期范围感兴趣,则忽略/抑制时间值。
  • '2014-03-31 23:59:59' 不是 2014-03-31 的最后一刻。 PostgreSQL 默认为microsecond precision in timestamps

标签: php sql postgresql timestamp


【解决方案1】:
pg_prepare($db, 'my_query', "
    select * 
    from table 
    where \"from\" >= $1 and to < $2::date + interval '1' day
");

由于from 是保留字,因此必须用双引号引起来。是的,您需要添加一天,以便包括 03-31 的一整天。

【讨论】:

    【解决方案2】:

    只需将integer 添加到date(这不适用于timestamp):

    pg_prepare($db, 'my_query', "
        select * 
        from table 
        where \"from\" >= $1 and \"to\" < $2::date + 1");
    

    另外,@Clodoaldo 写的关于 reserved wordsto 的内容也是保留的。
    明智的做法是使用保留字作为标识符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      相关资源
      最近更新 更多