1

我有两个表,我想通过表 A 中的列中bcnt的值更新表 b 中的列,acnt其中表 A 中的 worlds 列与表 B 中的单词列匹配,表 B 中的 id 与表 A 中的 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>

4

1 回答 1

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 个字符的值被截断为两个字符。因此,值不是“Cairo”,而是“Ca”(以适应 varchar2(2))。结果,您在联接中没有匹配项。

于 2012-12-09T15:45:13.437 回答