2012-12-09 95 views
1

我有兩個表我想要更新表0123在列bcnt中的表b的值由表A列acnt列中的值更新,其中表A中的世界列與表B中的字列匹配,並且id在表A中的表B匹配ID。基於另一個表中的值的更新表

create table a 
( 
    id number(9), 
    words varchar2(2), 
    acnt number(9) 
); 

insert into a values(1,'Cairo',20); 
insert into a values(1,'UK',10); 
insert into a values(2,'KL',2); 
insert into a values(2,'Cairo',2); 
insert into a values(2,'London',30); 
insert into a values(3,'Cairo',5); 
insert into a values(4,'KSA',15); 

create table b 
(
    id number(2), 
    words varchar2(20), 
    bcnt number 
); 

insert into b values(1,'Cairo',null); 
insert into b values(1,'UK',null); 
insert into b values(2,'KL',null); 
insert into b values(2,'Cairo',null); 
insert into b values(3,'Cairo',null); 
insert into b values(4,'KSA',null); 

我用這個SQL代碼,但它不正確。

update b 
set bcnt = (select acnt 
      from a 
      where a.id = b.id and a.words = b.words); 

預期結果:

1 cairo 20 
1 uk  10 
2 kl  2 
2 cairo 5 
4 ksa  12 

的SQL顯示我下面

SQL>/

     ID WORDS      BCNT 
---------- -------------------- ---------- 
     1 Cairo 
     1 UK       10 
     2 KL       2 
     2 Cairo 
     3 Cairo 
     4 KSA 

6 rows selected. 

SQL>

+1

你的SQL有什麼問題?它對我來說很好。 –

+2

(...除列名中的拼寫錯誤) – Mat

回答

0

那是你的SQL使用的word代替words作爲問題表定義?

update b 
    set bcnt=(select acnt from a where a.id=b.id and a.words=b.words); 

此外,您的數據類型在兩個表中不正確。你創建表的語句應該是一致的:

create table a (id number(9),words varchar2(20), acnt number); 
create table b (id number(9), words varchar2(20), bcnt number); 

正在發生的事情是,比第一臺2個字符的值被截斷爲兩個字符。所以,而不是'開羅'的值是'Ca'(以適應varchar2(2))。因此,您在聯接中沒有匹配。

+0

是的,你是對的。但我得到英國更新了10和KL 2的罰款,但其他是空的可能更新空值。 –

+0

我改變它是這樣的,但同樣只更新兩條記錄(更新b設置bcnt =(從a.id = b.id和upper(trim(a.words))= upper(trim(b.words) ))); –

相關問題