如何在Oracle中插入两个表的总和?

时间:2016-05-22 13:23:09

标签: sql oracle insert

我创建了以下表格:

create table AandB (
        code              varchar(9),
        total             number,
        CONSTRAINT pk_code PRIMARY KEY (code)
);

create table A (
        codeA              varchar(9),
        numberA              number,
        CONSTRAINT pk_codeA PRIMARY KEY (codeA)
);

create table B (
        codeB              varchar(9),
        numberB            number,
        CONSTRAINT pk_codeB PRIMARY KEY (codeB)
);

我插入了以下数据:

insert into AandB(code) values('0x1');
insert into AandB(code) values('0x2');
insert into AandB(code) values('0x3');

insert into A(codeA, numberA) values('0x1',5);
insert into A(codeA, numberA) values('0x2',6);
insert into A(codeA, numberA) values('0x3',1);

insert into B(codeB, numberB) values('0x1',8);
insert into B(codeB, numberB) values('0x2',10);
insert into B(codeB, numberB) values('0x3',12);

问题是:如何在列#34; total"中插入numberA + numberB表格#34; AandB",即:

  

0X1 = 13

     

0X2 = 16

     

0X3 = 13

感谢您提出任何建议或答案,祝您有个愉快的一天!

1 个答案:

答案 0 :(得分:1)

好吧,只需根据AandBA之间的联接更新B

UPDATE AandB ab
SET ab.total = (SELECT a.numberA + b.numberB
                FROM A
                INNER JOIN B
                 ON(a.codeA = b.codeB)
                WHERE a.codeA = ab.code)

如果AB表不一定包含所有AandB代码,那么您应该添加一个where子句来过滤它们:

UPDATE AandB ab
SET ab.total = (SELECT a.numberA + b.numberB
                FROM A
                INNER JOIN B
                 ON(a.codeA = b.codeB)
                WHERE a.codeA = ab.code)
WHERE EXISTS(SELECT 1 FROM A
             INNER JOIN B
              ON(a.codeA = b.codeB)
             WHERE a.codeA = ab.code)