2017-06-10 100 views
0

Postgres 9.5使用第一個WITH AS語句在第二個AS語句中的結果

如何以可以使用第一個WITH AS的結果的方式使用WITH語句?現在我越來越:

psql:query.sh:7: ERROR: missing FROM-clause entry for table "foo2" 
LINE 6: ...INTO copy_on_write(id, images, posted_by) VALUES (foo2.id, f... 

WITH foo1 AS (SELECT listings.id, listings.images, listings.posted_by 
    FROM listings WHERE listings.posted_by = 10209280753550922::text 
    AND listings.id = 5), 
foo2 AS (SELECT foo1.id, foo1.images, users.internal_id FROM foo1 
JOIN users ON users.id = foo1.posted_by) 
INSERT INTO copy_on_write(id, images, posted_by) VALUES (foo2.id, foo2.images, foo2.internal_id) 

回答

1

你只需要INSERT . . . SELECT,不INSERT . . . VALUES

WITH foo1 AS (
     SELECT l.id, l.images, l.posted_by 
     FROM listings l 
     WHERE l.posted_by = 10209280753550922::text AND l.id = 5 
    ), 
    foo2 AS (
     SELECT foo1.id, foo1.images, u.internal_id 
     FROM foo1 JOIN 
      users u 
      ON u.id = foo1.posted_by 
    ) 
INSERT INTO copy_on_write(id, images, posted_by) 
    SELECT foo2.id, foo2.images, foo2.internal_id 
    FROM foo2;