简体   繁体   中英

Update all rows for one column in a table with data in another table

I appreciate any advice on this..

I have two tables where I have to update a column in my primary table with data that resides in another secondary table. I cannot rely on views, etc as this data has to be able to be edited by the user in APEX in the future. I am basically pre-populating the data for the users to reduce their manual entry.

Primary Table = Table 1

Secondary Table = Table 2

Columns to be updated in Table 1 = FTE_ID , ACCOUNT_TYPE

Columns where the data will come from Table 2 = R_ID , ACCOUNT_TYPE

Common column in both tables = TABLE1.FID AND TABLE2.FID

Here is what I have tried, but I get "single-row subquery returns more than one row" because there are multiple table1.fid rows in table1 . I basically want to perform this update for ALL rows where TABLE1.FID = TABLE2.FID .

Here is my attempt:

UPDATE TABLE1
SET TABLE1.FTE_ID = 
(SELECT TABLE2.R_ID FROM TABLE2 WHERE TABLE1.FID = TABLE2.FID);

Error:

single-row subquery returns more than one row

Thanks for your help,

You can fix the proximate problem by using aggregation or row number:

UPDATE TABLE1
    SET TABLE1.FTE_ID = (SELECT MAX(TABLE2.R_ID)
                         FROM TABLE2
                         WHERE TABLE1.FID = TABLE2.FID
                        );

The subquery can only return one row; it is an "arbitrary" value from the possible matching values.

If the field is a character field and you want all matching values, then perhaps listagg is more appropriate:

UPDATE TABLE1
    SET TABLE1.FTE_ID = (SELECT LISTAGG(t2.R_ID, ',') WITHIN GROUP (ORDER BY t2.R_ID)
                         FROM TABLE2 t2
                         WHERE TABLE1.FID = t2.FID
                        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM