2

我正在尝试table1.column_name1使用查询的数据结果进行更新

Select ID, column_name1 
from table2  
union  
Select ID, column_name2 
from table3

但我收到此错误:

ORA-01427: 单行子查询返回多于一行

请有任何建议,谢谢:)

使用以下数据表:

表格1

ID             column_name1            
----------------------------
26                 null          
30                 null                  
34                 null   

表2

ID             column_name1            
---------------------------
26                 fix          
30                 var                  
34                 fix        

表3

ID             column_name2            
----------------------------
26                 fix          
30                 null                 
34                 fix   

期望的结果:

ID             column_name1            
-----------------------------
26                 fix
30                 var
34                 fix

询问:

UPDATE table1 
SET table1.column_name1 = (SELECT b.column_name1 
                           FROM table1 f 
                           JOIN 
                              (SELECT ID, column_name1 
                               FROM table2  
                               UNION
                               SELECT ID, column_name2 
                               FROM table3) b ON f.ID = b.ID);
4

2 回答 2

2

您可以使用查询JOIN而不是UNION这样,以便能够处理空值,这会导致UPDATE语句中的行过多,其中WHERE还需要条件

UPDATE table1 t1
   SET t1.column_name1 = ( SELECT NVL(t3.column_name2, t2.column_name1)
                             FROM table2 t2
                             JOIN table3 t3
                               ON t3.ID = t2.ID
                            WHERE t3.ID = t1.ID )  
 WHERE EXISTS
           ( SELECT *
               FROM table2 t2
               JOIN table3 t3
                 ON t3.ID = t2.ID
              WHERE t3.ID = t1.ID ) 

Demo

于 2020-11-26T17:48:47.317 回答
1

您正面临问题,因为您试图将两个值(相同/不同)分配给单个值。

您可以merge按如下方式使用:

Merge into table1 t1
Using (SELECT coalesce(t2.column_name1, t3.column_name2) as column_name, t2.id
         FROM table2 t2
         JOIN table3 t3 ON t3.ID = t2.ID) src
ON (src.ID = t1.ID)
When matched then 
Update set t1.column_name1 = src.column_name
于 2020-11-26T18:35:55.587 回答