Oracle SQL相关更新

时间:2013-03-26 15:22:53

标签: sql oracle sql-update subquery

我有三张桌子:

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

现在我想要的是用t3.d更新t1.c.但我不能只使用t1.c = t3.c从t3更新t1。我也必须通过t3.b = t2.b和t1.a = t2.a。

我尝试过这样的事情:

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);

此代码生成error-msg:ORA-01427:单行子查询返回多行

4 个答案:

答案 0 :(得分:2)

如果t1和t2之间或t2和t3之间存在一对多的关系,那么t1中的每一行都会得到很多匹配。如果您知道t3中属于t1中同一行的所有行在d中具有相同的值,那么您可以使用DISTINCT删除(相同的)重复项。

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);

答案 1 :(得分:1)

您有一个返回多行的子查询。使用rownum只能获得一行:

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);

答案 2 :(得分:1)

很抱歉这个混乱,但我解决了它:

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)

答案 3 :(得分:0)

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);