使用 cte (postgresql) 的结果进行更新

Update with result from cte (postgresql)

如果有任何记录是更早的日期,我想更新工作日期。尝试使用 CTE 实现此目的:

CREATE TABLE job
    (jobid int4, jobdate date);

INSERT INTO job
    (jobid, jobdate)
VALUES
    (1, '2016-02-01'),
    (2, '2016-02-01'),
    (3, '2016-02-01'),
    (4, '2016-02-01')
;

CREATE TABLE rec
    (recid int4, recjob int4, recdate date);

INSERT INTO rec
    (recid, recjob, recdate)
VALUES
    (1,1,'2016-02-01'),
    (2,2,'2016-01-01'),
    (3,3,'2016-02-01'),
    (4,4,'2016-02-01')
;

作业编号 2 的记录日期早于作业日期。所以我想用记录日期更新这个工作。

WITH      cte AS
          (SELECT jobid,least(min(recdate),jobdate)
FROM      job
LEFT JOIN rec ON recjob=jobid
GROUP BY  jobid,jobdate
HAVING    least(min(recdate),jobdate)<jobdate)

选择 cte 表明应该更新作业 2 是正确的

SELECT * FROM cte

但更新时出现错误:缺少 table "cte"

的 FROM 子句条目
UPDATE job 
SET    jobdate=cte.date 
WHERE  jobid IN (SELECT jobid FROM cte)

SQLFiddle: http://sqlfiddle.com/#!15/e9ae6/8

我从来没有使用过更新的 cte,所以我需要一些帮助来理解这一点。

TIA,

尝试使用以下语法 UPDATE

UPDATE job
SET jobdate = cte.date
FROM cte
WHERE job.jobid = cte.jobid

语法如下:

WITH cte AS (
    SELECT * FROM ...
)
UPDATE table_to_update
SET column_from_table_to_update = cte.some_column
FROM cte
WHERE table_to_update.id = cte.id