Populating database table column with corresponding values from another table in PostgreSQL

我只是一个虾纸丫 提交于 2019-12-02 21:49:37

问题


Table 1 is 'z_scrapestorm_rentals' and table 2 is 'pcpao_cols'. They both have address columns named 'address_1_line_trunc' and 'address_one_line' respectively.

Both tables also have a column named 'web_strap', but only 'pcpao_cols' has values in this column that are not null.

I want these values from pcpao_cols.web_strap copied into z_scrapestorm_rentals.web_strap for rows where z_scrapestorm_rentals.address_1_line_trunc matches pcpao_cols.address_one_line.

I used a few different queries to do this, but they either appear to run successfully (no errors) without actually updating any values or I get errors.

Method 1:

(no errors and DBeaver says 124 rows were updated but the 'web_strap' column in z_scrapestorm_rentals table still doesn't have any values in it... I know matches exist since I can successfully query them, but I just can't seem to update the table.)

UPDATE z_scrapestorm_rentals
    SET web_strap = z_scrapestorm_rentals.web_strap
    FROM pcpao_cols
    WHERE z_scrapestorm_rentals.address_1_line_trunc ILIKE pcpao_cols.address_one_line;

Method 2:

(syntax error at or near 'SELECT')

UPDATE z_scrapestorm_rentals
    SELECT
        z_scrapestorm_rentals.*,
        pcpao_cols.web_strap
    FROM z_scrapestorm_rentals
LEFT JOIN pcpao_cols
ON z_scrapestorm_rentals.address_1_line_trunc = pcpao_cols.address_one_line;

Method 3:

(error: invalid reference to FROM-caluse entry for table "z_scrapestorm_rentals"...Hint: there is an entry for table "z_scrapestorm_rentals", but it cannot be referenced from this part of the query. Position 89)

INSERT INTO z_scrapestorm_rentals (web_strap)
    SELECT web_strap
    FROM pcpao_cols
    WHERE z_scrapestorm_rentals.address_1_line_trunc ILIKE pcpao_cols.address_one_line;

Any help is appreciated.


回答1:


Okay, so I answered my own question and inserted the web_strap values from the other table into the target table by using the following query:

UPDATE z_scrapestorm_rentals
    SET web_strap = pcpao_cols.web_strap
    FROM
        pcpao_cols
    WHERE Z_scrapestorm_rentals.address_1_line_trunc 
ILIKE pcpao_cols.address_one_line
    RETURNING pcpao_cols.web_strap;

What was missing from my original query I detailed in my question's "method 1" was the RETURNING keyword.



来源:https://stackoverflow.com/questions/54193055/populating-database-table-column-with-corresponding-values-from-another-table-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!