Oracle multi-table association update (update multi-table association)

From: http://blog.csdn.net/leeboy_wang/article/details/8099942


Oracle does not have update from syntax, and it can be implemented in two ways:
1. Use subquery:
     update A  
     SET field 1= (select field expression from B WHERE ...),  
       field 2 = (select field expression from B WHERE ...)  
     WHERE logical expression 

   UPDATE multiple fields are written in two ways:


way of writing:

UPDATE table_1 a
   SET col_x1 = (SELECT b.col_y1, b .col_y2 FROM table_2 b WHERE b.col_n = a.col_m),
       col_x2 = (SELECT b.col_y2 FROM table_2 b WHERE b.col_n = a.col_m)
WHERE EXISTS (SELECT * FROM table_2 b WHERE b.col_n = a.col_m )

or

UPDATE table_1 a
   SET col_x1 = (SELECT b.col_y1, b.col_y2 FROM table_2 b WHERE b.col_n = a.col_m),
       col_x2 = (SELECT b.col_y2 FROM table_2 b WHERE b.col_n = a.col_m)
WHERE a.col_m=(SELECT b.col_n FROM table_2 b WHERE b.col_n = a.col_m)


Writing method 2:

UPDATE table_1 a
   SET (col_x1 , col_x2) = (SELECT b.col_y1, b.col_y2 FROM table_2 b WHERE b.col_n = a.col_m)
WHERE EXISTS (SELECT * FROM table_2 b WHERE b.col_n = a.col_m);

or

UPDATE table_1 a
   SET (col_x1 , col_x2) = (SELECT b.col_y1, b.col_y2 FROM table_2 b WHERE b.col_n = a.col_m)
WHERE a.col_m=(SELECT b.col_n FROM table_2 b WHERE b.col_n = a.col_m)


Note:

1 . The value for a subquery can only be a unique value, not multiple values.
        2. Subqueries In most cases, the last where EXISTS clause is important, otherwise you will get wrong results. And the where EXISTS clause can be replaced by another method, as above. The last clause is a restriction on the updated records in table a. If there is no such sentence, for a record in table a, if there is no corresponding record in table b, the updated field of the record will be updated to null. The where EXISTS clause is to exclude the records in the a table from being updated.

2. Use view:


UPDATE (SELECT A.NAME ANAME,B.NAME BNAME FROM A,B WHERE A.ID=B.ID)
SET ANAME=BNAME;

   Note:

    1. Restrictions on view update:
    if the view is based on multiple table join, the user's ability to update (update) view records will be limited. A view's base table cannot be updated unless the update involves only one table and the view column contains the entire primary key of the updated table.


In addition, the from clause of Delete in Oracle does not have the function of multi-table join, and can only be done by sub-query:
delete from table A where exists (select * from table B where table A.empid=table B.empid )
delete from table A where table A.empid in (select empid from table B)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326533835&siteId=291194637