简体   繁体   中英

Update a Table with value from another Table. PL SQL

I frequently use below JOIN and UPDATE to bring value from one table to another in TSQL.

UPDATE T1
SET T1.Mobile = T2.Mobile
FROM Table1 T1 INNER JOIN Table2 T2 ON T1.ID = T2.ID

Then I found in PL SQL, the syntax to do such update is either by using a MERGE, or a nest statement.

Either way appear to be not as straight forward as the TSQL solution, which makes me wondering if PL SQL developer actually perform such cross table update, or if there is other development principle making such update unnecessary.

One comment I got from a PL SQL developer is that they'd rather create a view like

CREATE VIEW MyView AS
(
SELECT T1.Filed1, T1.Field2, T2.Mobile 
FROM Table1 T1 INNER JOIN Table2 T2 ON T1.ID = T2.ID
);

This looks like a viable solution taking the fact that joining does not introduce duplicates into Table1/MyView, or putting a dedup logic above. One obvious benefit for this is that we can continue refreshing Table2.Mobile, and MyView will always have the updated value.

I am seeking comment on coding principle. :)

You may update using a correlated subquery:

UPDATE Table1 T1
SET T1.Mobile = (SELECT Mobile FROM Table2 T2 WHERE T1.ID = T2.ID);

You should use this query to make an inner join. Without the where clause it's just a left join, that can consists of empty mobile data from T2

UPDATE Table1 T1
SET T1.Mobile = (SELECT min(Mobile) FROM Table2 T2 WHERE T1.ID = T2.ID)
where T1.ID in (SELECT T2.ID FROM Table2 T2)
;
  • And with the max(Mobile) you prevent to get an error when you have a 1:n relation for T1:T2.
  • To speedup the statements you should create indexes on T1.ID and T2.ID

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