postgresql - 将查询SELECT EXTRACT的结果插入另一个表中

时间:2014-03-13 16:29:12

标签: postgresql

我在postgresql(table1)中有以下表格:

 Var1,
 var2,
 var3,
 timestamp1  timestamp without time zone NOT NULL,
 timestamp2  timestamp without time zone NOT NULL,
 diff double precision,

列diff是空的。

我通过以下代码计算变量diff: SELECT EXTRACT(EPOCH FROM((timestamp1 - timestamp2)/ 1800))

我想在表1的变量diff中插入此操作的结果。

我编写以下代码,但不起作用......

CREATE TEMPORARY TABLE temptablename AS
SELECT EXTRACT(EPOCH FROM ((timestamp1 – timestamp2)/1800)) AS diff2 from table1;

INSERT INTO table1 (diff) SELECT diff2 FROM temptablename;

ERROR:  null value in column "" violates not-null constraint
DETAIL:  Failing row contains (null, null, null, null, null,83).

1 个答案:

答案 0 :(得分:1)

假设你的算术是正确的,那么听起来就像你只需要一个更新声明一样。

update table1
set diff = extract(epoch from ((timestamp1 – timestamp2)/1800))
where diff is null;

WHERE子句不是必需的,因为您已经知道列是空的。但是它可以防止在运行该语句时第二次时覆盖值。