2015-12-10 187 views
0

表1更新甲骨文

Tripid sequence Pattern 
    1  1  
    1  2 
    1  3 
    2  1 
    2  2 

表2

Tripid Pattern 
    1  A 
    2  B 

我試圖更新表1模式,最終的結果應該是:

Tripid sequence Pattern 
    1  1  A 
    1  2  A 
    1  3  A 
    2  1  B 
    2  2  B 

的代碼我用:

update table1 
set table1.pattern = 
    (select pattern from table2 where table1.tripid = table2.tripid) 
where exists 
    (select pattern from table2 where table1.tripid = table2.tripid) 

Oracle數據庫錯誤:ORA-01427:單行子查詢返回多行

如何正確地做到這一點在Oracle 10g更多?

回答

1

您可以使用MERGE聲明。

查詢

select * from t1 

Result

| TRIPID | SEQ | PATTERN | 
|--------|-----|---------| 
|  1 | 1 | (null) | 
|  1 | 2 | (null) | 
|  1 | 3 | (null) | 
|  2 | 1 | (null) | 
|  2 | 2 | (null) | 

查詢

merge into t1 
using t2 
on (t1.tripid = t2.tripid) 
when matched then update 
set pattern = t2.pattern 

查詢

select * from t1 

Result

| TRIPID | SEQ | PATTERN | 
|--------|-----|---------| 
|  1 | 1 |  A | 
|  1 | 2 |  A | 
|  1 | 3 |  A | 
|  2 | 1 |  B | 
|  2 | 2 |  B | 
+0

怎麼來自另一個表的更新在oracle中不能正常工作? – Sailormoon

0

也許,TRIPID是不是在表2獨特?

它在你的例子中,但它在你的真實數據中是唯一的嗎?

DROP table table1; 
create table table1(tripid number, sequence number, pattern CHAR(1)); 
insert into table1 values (1,1,null); 
insert into table1 values (1,2,null); 
insert into table1 values (1,3,null); 
insert into table1 values (2,1,null); 
insert into table1 values (2,2,null); 

DROP table table2; 
create table table2(tripid number, pattern CHAR(1)); 
insert into table2 values (1,'A'); 
insert into table2 values (2,'B'); 

commit; 

select table2.tripid, table2.pattern from table2,table1 where table1.tripid = table2.tripid; 


update table1 
set table1.pattern = 
    (select pattern from table2 where table1.tripid = table2.tripid) 
where exists 
    (select pattern from table2 where table1.tripid = table2.tripid); 

commit; 

select * from table1; 

回報:

Table dropped. 
Table created. 
1 row created. 
1 row created. 
1 row created. 
1 row created. 
1 row created. 
Table dropped. 
Table created. 
1 row created. 
1 row created. 
Commit complete. 

    TRIPID PATTERN 
---------- ------- 
     1 A  
     1 A  
     1 A  
     2 B  
     2 B  

5 rows selected. 
5 rows updated. 


    TRIPID SEQUENCE PATTERN 
---------- ---------- ------- 
     1   1 A  
     1   2 A  
     1   3 A  
     2   1 B  
     2   2 B  

5 rows selected. 

這證明具有良好的數據,甲骨文(和您的查詢)完美。

基督教