使用WITH子句查询Postgres"缺少FROM子句条目"错误

Are*_*bre 23 sql postgresql with-clause

我试图在Postgres 9.1.3中使用此查询:

WITH stops AS (
    SELECT citation_id,
           rank() OVER (ORDER BY offense_timestamp,
                     defendant_dl,
                     offense_street_number,
                     offense_street_name) AS stop
    FROM   consistent.master
    WHERE  citing_jurisdiction=1
)

UPDATE consistent.master
SET arrest_id = stops.stop
WHERE citing_jurisdiction=1
  AND stops.citation_id = consistent.master.citation_id;
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

ERROR:  missing FROM-clause entry for table "stops"
LINE 12: SET arrest_id = stops.stop
                         ^

********** Error **********

ERROR: missing FROM-clause entry for table "stops"
SQL state: 42P01
Character: 280
Run Code Online (Sandbox Code Playgroud)

我真的很困惑.根据Postgres文档,WITH子句显示正确.如果我在WITH子句中单独运行查询,我会得到正确的结果.

mu *_*ort 30

精细手册:

有两种方法可以使用数据库中其他表中包含的信息来修改表:使用子选择,或在FROM子句中指定其他表.

所以你只需要一个FROM子句:

WITH stops AS (
    -- ...
)
UPDATE consistent.master
SET arrest_id = stops.stop
FROM stops -- <----------------------------- You missed this
WHERE citing_jurisdiction=1
  AND stops.citation_id = consistent.master.citation_id;
Run Code Online (Sandbox Code Playgroud)

错误信息甚至说得多:

错误:缺少FROM-clause条目表"停止"

  • 你是对的!他们需要在这里给出"傻瓜"点.我想我只赚了一个. (3认同)
  • @ArenCambre:我认为如果有这样的事情,我们都会有过多的"傻瓜"点:)一些最困难的问题就是你面前的那些问题. (3认同)
  • 非常好的答案.只是一个小问题:它应该是FROM停止而不是FROM停止,对吧? (2认同)