DB2如何根据其他2个表将值插入表中?

时间:2016-04-03 18:26:00

标签: sql database db2

我有3张桌子:

表A:obj_1(varchar),rlt(varchar),obj_2(varchar)

表B:r_id(int),r_obj(varchar)

表C:obj1(int),action(varchar),obj2(int)

我需要插入表C,因此它是表A的精确副本,除了obj_1和obj_2名称之外,它使用表C中该对象(r_id)的引用号。

INSERT into tablec (obj1, action, obj2) ((select r_id from tableb, tablea 
where tablea.obj_1 = tableb.r_obj), (select rlt from tablea), (select r_id    
from tableb, tablea where tablea.obj_1 = tableb.r_obj))

2 个答案:

答案 0 :(得分:0)

您可以将insert-select语句与加入referenceproject的查询一起使用:

INSERT INTO tablec (obj1, action, obj2)
(SELECT b1.r_id, a.action, b2.r_id
 FROM   tablea a
 JOIN   tableb b1 ON a.obj1 = b1.r_obj
 JOIN   tableb b2 ON a.obj2 = b2.r_obj)

答案 1 :(得分:0)

我必须使用解决方法,因为db2有一些限制: 我用2个临时视图作为我的目标的垫脚石。

我单独进行2个连接:

create view temp1 (a, b) as (select tablea.p_id, tableb.r_id from tablea
tableb where tablea.obj_1 = tableb.r_obj)

create view temp2 (c, d, rlt) as (select tablea.p_id, tableb.r_id, tablea.rlt
from tablea, tableb where tablea.obj_2 = tableb.r_obj)

然后我使用一个插入元素根据表格中的PK组合这两个

INSERT INTO final (obj_1, rlt, obj_2) 
(select temp1.b, temp2.rlt, temp2.d from temp1 join temp2 on temp1.a = temp2.c)