PostgreSQL,SQL状态:42601

时间:2014-06-16 20:38:12

标签: postgresql

我想使用select从2个表(segment和wgs)中取值来插入表(电路)。我的问题:

INSERT INTO circuit (id_circuit, description, date_start, date_end, speed,
length, duration)
SELECT (seg.id_segment, cir.nomcircuit, seg.date_start, seg.date_end, seg.speed_average,
cir.shape_leng, (seg.date_end - seg.date_start)) 
FROM segment seg, wgs cir where seg.id = 13077

我的表:电路:

CREATE TABLE circuit
(
  id serial NOT NULL,
  id_circuit integer,
  description character varying(50),
  date_start time without time zone,
  date_end time without time zone,
  speed double precision,
  length double precision,
  duration double precision,
  CONSTRAINT circuit_pkey PRIMARY KEY (id)
)

段:

CREATE TABLE segment
(
  id serial NOT NULL,
  id_segment integer,
  date_start timestamp without time zone,
  date_end timestamp without time zone,
  speed_average double precision,
  mt_identity character varying,
  truck_type character varying,
  CONSTRAINT segment_pkey PRIMARY KEY (id)
)

WGS:

CREATE TABLE wgs
(
  id serial NOT NULL,
  nomcircuit character varying(50),
  shape_leng numeric,
  CONSTRAINT wgs_pkey PRIMARY KEY (id)
)

但是当我运行查询时,会出现此错误:

ERROR:  INSERT has more target columns than expressions
LINE 1: INSERT INTO circuit (id_circuit, description, dat...
                                                    ^
HINT:  The insertion source is a row expression containing the same number of columns
expected by the INSERT. Did you accidentally use extra parentheses?

到目前为止,我可以看到,我没有额外的括号,我仔细检查了列数据类型,并确保它们匹配和各种尝试,但我仍然不明白为什么错误来了。 PS:13077只是用一个值来尝试,我相信我有。

1 个答案:

答案 0 :(得分:2)

这构造了一个匿名复合值:

select (1, 'a');

例如:

=> select (1, 'a');
  row  
-------
 (1,a)
(1 row)

=> select row(1, 'a');
  row  
-------
 (1,a)
(1 row)

请注意,这是一个复合值,而不是多个值。

来自fine manual

  

<强> 8.16.2。综合价值输入

     

要将复合值写为文字常量,请将字段值括在括号中并用逗号分隔。您可以在任何字段值周围加上双引号,如果它包含逗号或括号,则必须这样做   [...]
  ROW表达式语法也可用于构造复合值。在大多数情况下,这比使用字符串文字语法要简单得多,因为您不必担心多层引用。我们已经使用了上面的方法:

ROW('fuzzy dice', 42, 1.99)
ROW('', 42, NULL)
     

ROW关键字实际上是可选的,只要表达式中有多个字段,因此可以简化为:

('fuzzy dice', 42, 1.99)
('', 42, NULL)

Row Constructors部分也可能会引起关注。

当你这样说时:

INSERT INTO circuit (id_circuit, description, date_start, date_end, speed,
length, duration)
SELECT (...)
FROM segment seg, wgs cir where seg.id = 13077

您的SELECT子句只有一列,因为整个(...)表达式代表一个值。解决方案是简单地删除这些括号:

INSERT INTO circuit (id_circuit, description, date_start, date_end, speed, length, duration)
SELECT seg.id_segment, ..., (seg.date_end - seg.date_start)
FROM segment seg, wgs cir where seg.id = 13077