Oracle SQL correlated update

2019-02-27 13:09发布

I got three tables:

t1.columns: a,c
t2.columns: a,b
t3.columns: b,c,d

Now what I want is to update t1.c with t3.d. But I can't just update t1 from t3 using t1.c = t3.c I also have to go though t3.b = t2.b and t1.a = t2.a.

I've tried something like this:

UPDATE table1 t1
   SET t1.c = (select t3.d
               from table2 t2, table3 t3
               where t2.b = t3.b and t1.a = t2.a)                                  
 WHERE EXISTS ( SELECT 1 FROM table2 t2, table3 t3 WHERE t1.c = t3.c and t1.a = t2.a);

This code generates error-msg: ORA-01427: single-row subquery returns more than one row

4条回答
我只想做你的唯一
2楼-- · 2019-02-27 13:39

If there is a one-to-many relationship between t1 and t2 or between t2 and t3 you will get many matches for each row in t1. If you know that all rows in t3 that belong to the same row in t1 have the same value in d, then you can use DISTINCT to remove (identical) duplicates.

UPDATE table1 t1
   SET t1.c = (select DISTINCT t3.d
               from table2 t2, table3 t3
               where t2.b = t3.b and t1.a = t2.a)                                  
 WHERE EXISTS ( SELECT 1 FROM table2 t2, table3 t3 WHERE t1.c = t3.c and t1.a = t2.a);
查看更多
等我变得足够好
3楼-- · 2019-02-27 13:47
UPDATE table1 t1
   SET t1.c = (select MAX(t3.d)
               from table2 t2, table3 t3
               where t2.b = t3.b and t1.a = t2.a)                                  
 WHERE EXISTS ( SELECT 1 FROM table2 t2, table3 t3 WHERE t1.c = t3.c and t1.a = t2.a);
查看更多
smile是对你的礼貌
4楼-- · 2019-02-27 13:51

Sorry for the confusion but I solved it:

UPDATE table t1
SET t1.c = (select t3.d from table3 t3, table2 t2
                          where t1.a = t2.a and t2.b = t3.b and t3.c = t1.c)
 WHERE EXISTS ( SELECT 1 FROM table1 t1, table2 t2 WHERE t1.a = t2.a and t2.b = t3.b and t3.c = t1.c)
查看更多
The star\"
5楼-- · 2019-02-27 13:55

You have a subquery that is returning more than one row. Use rownum to get just one row:

UPDATE table1 t1
   SET t1.c = (select d
               from (select t3.d
                     from table2 t2 join table3 t3
                          on t2.b = t3.b 
                     where t1.a = t2.a
                    ) t
                where rownum = 1
               )                                
 WHERE EXISTS ( SELECT 1 FROM table2 t2, table3 t3 WHERE t1.c = t3.c and t1.a = t2.a);
查看更多
登录 后发表回答