【问题标题】:Update table based on values in another table根据另一个表中的值更新表
【发布时间】:2012-11-27 03:34:53
【问题描述】:

我有两个表我想通过表 A 中的列 acnt 中的值更新表 b 中的列 bcnt,其中表 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>

【问题讨论】:

  • 你的 SQL 出了什么问题?我觉得没问题。
  • (...除了列名中的拼写错误)

标签: sql plsql oracle11g sql-update


【解决方案1】:

问题是你的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))。结果,您在联接中没有匹配项。

【讨论】:

  • 是的,你是对的。但是我将 UK 更新为 10,将 KL 更新为 2,这很好但是 OTHERS 是 EMPTY 可能由 NULL 值更新。
  • 我像这样改变它,但也同样只更新两条记录(更新 b 集 bcnt=(从 a.id=b.id 和上选择 a.id=b.id 和上(trim(a.words))=上(修剪(b.words)));
猜你喜欢
  • 1970-01-01
  • 2012-09-05
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多