2

我有三张桌子:

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

此代码生成错误消息:ORA-01427:单行子查询返回多于一行

4

4 回答 4

3

如果 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);
于 2013-03-26T15:28:15.493 回答
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);
于 2013-03-26T15:54:23.050 回答
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)
于 2013-03-27T09:06:53.983 回答
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);
于 2018-01-17T21:58:45.860 回答