【问题标题】:PostgreSQL how to concat interval value '2 days'PostgreSQL如何连接间隔值'2天'
【发布时间】:2012-03-11 16:36:33
【问题描述】:

在 PostgreSQL 中,我想将 current_timestampinterval 连接起来,如下所示:

select current_timestamp + interval 2||' days'

但是当我这样做时,我得到一个错误:

[Err] ERROR:  syntax error at or near "2"
LINE 1: select current_timestamp + interval 2||' days'

但如果我这样做,它可以正常工作:

select current_timestamp + interval '2 days'

为什么一个有效,而另一个无效?

参考以下页面 http://www.postgresql.org/docs/8.0/static/functions-datetime.html

【问题讨论】:

  • 真的在使用 8.0 吗? (您指向手册的链接使用该版本)

标签: postgresql datetime intervals


【解决方案1】:

部分问题在于间隔的标准 SQL 表达式引用了数字,而不是关键字。所以你必须小心。

select current_date, current_date + interval '2' day;
--
2012-02-21   2012-02-23 00:00:00

在 PostgreSQL 中,引用 '2 day' 和 '2 days' 也可以。所以你可能会认为'2' || 'days' 是等价的,但不是。

select current_date, current_date + interval '2' || ' days';
--
2012-02-21   2012-02-21 00:00:02 days

正如 A.H. 所说,解决方案是将结果字符串转换为间隔。

您也可以使用变量代替 2。这会生成 2012 年的日历。

-- 0 to 365 is 366 days; 2012 is a leap year.
select ('2012-01-01'::date + (n || ' days')::interval)::date calendar_date
from generate_series(0, 365) n;

我使用最后的转换日期,因为 date + interval 返回一个时间戳。

【讨论】:

    【解决方案2】:

    请试试这个语法:

    select current_timestamp + ( 2 || ' days')::interval;
    

    甚至这个:

    select current_timestamp + 2 * interval '1 day';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多