Update with Join query in Oracle

2020-01-26 12:50发布

问题:

what is wrong in query? (it executes indefinitely)

UPDATE table1 t1 SET (t1.col,t1.Output) = (
  SELECT t2.col, t3.Output + t2.col
  FROM tabl2 t3 
  LEFT JOIN table1 t2 ON t3.Join_Key = t2.Join_Key
  WHERE t2.col is not NULL);

Please, help me.

回答1:

Your query does not make a whole lot of sense with the generic table1, table2, and join_key references.

If this is not what you are looking for, it would be helpful to have some sample data to get a better idea of what results you are looking for.

update table1 t1
   set t1.col = (select t2.col
                 from table2 t2
                 where  t1.join_key = t2.join_key(+)  
                  and  t1.col is not null),
       t1.output = (select t2.output + t1.col
                    from  table2 t2
                   where  t1.join_key = t2.join_key(+)  
                     and  t1.col is not null);


回答2:

Unless your SELECT subquery returns a single row, your UPDATE statement should fail with the error

ORA-01427: single-row subquery returns more than one row

Generally, whey you have a correlated update, you need some condition that relates rows in the outer table T1 to rows in the inner subquery in order to ensure that the subquery returns a single row. That would generally look something like

UPDATE table1 t1 SET (t1.col,t1.Output) = (
  SELECT t2.col, t3.Output + t2.col
  FROM tabl2 t3 
  LEFT JOIN table1 t2 ON t3.Join_Key = t2.Join_Key
  WHERE t2.col is not NULL
    AND t1.some_key = t2.some_key);

Finally, this UPDATE statement is updating every row in T1. Is that what you intend? Or do you only want to update the rows where, for example, you find a match in your subquery?