从cte(postgresql)更新结果

时间:2016-04-28 07:51:27

标签: sql postgresql postgresql-9.1

如果有任何记录是较早的日期,我想更新工作日期。尝试使用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

但更新会产生错误:缺少表“cte”

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

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

我从未使用cte进行更新,所以我需要一些帮助才能理解这一点。

TIA,

3 个答案:

答案 0 :(得分:27)

使用以下语法尝试UPDATE;

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

答案 1 :(得分:5)

语法如下:

JSON.stringify(arr);

答案 2 :(得分:1)

cte是一张桌子。一种解决方案是对它进行选择:

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

UPDATE    job 
SET       jobdate=(SELECT date from cte)
WHERE     jobid IN (SELECT jobid from cte)

或使用UPDATE ... FROM语法