Postgres在一个查询中使用两个select语句时引发错误

时间:2014-11-18 06:19:01

标签: sql common-table-expression postgresql-9.2

我创建了一个包含两个Fields Date和name的Table。我已经编写了一个insert语句来插入带有来自不同表的两个select语句的值。我的查询如下:

insert into temptable with date as (select date from generate_series('2014-04-01', 
  '2014-04-30', '1 day'::interval) as date),name as (select name from table12 where id=1912)

但是Query返回的错误如下:

ERROR:  syntax error at end of input
LINE 3: ... date),name as (select name from table12 where id=1912)
                                                                  ^

查询有问题吗?这是在查询中使用'with'的正确方法吗?

1 个答案:

答案 0 :(得分:0)

您需要从公用表中选择表达式:

将公用表表达式(with部分)放在插入之前:

insert into temptable
with date as (
   select date 
   from generate_series('2014-04-01','2014-04-30', '1 day'::interval) as date
),
name as (
   select name 
   from table12 
   where id=1912
)
select * 
from date 
  cross join name;

作为替代方案,您可以将CTE放在插入物的前面(我个人更喜欢):

with date as (
   select date 
   from generate_series('2014-04-01','2014-04-30', '1 day'::interval) as date
),
name as (
   select name 
   from table12 
   where id=1912
)
insert into temptable
select * 
from date 
  cross join name;

不确定您希望如何连接CTE的两个部分。