【问题标题】:DB2 How to insert values into a table based on 2 other tables?DB2 如何将值插入基于 2 个其他表的表中?
【发布时间】:2016-04-03 18:26:00
【问题描述】:

我有 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))

【问题讨论】:

  • 您的解释和示例 SQL 不匹配。您能否分享正确的表格结构、一些示例数据以及您希望从该数据中获得的结果?
  • @Mureinik 完成!我的坏..

标签: sql database db2


【解决方案1】:

您可以将插入选择语句与连接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)

【讨论】:

  • 谢谢!这很好,允许我向所有 3 列添加多行。但是,因为 ON 子句仅针对 obj_1 设置,所以在 tablec 中,obj_1 和 obj_2 是彼此的副本,但实际上,我还需要为 a.obj_2 获取正确的 b.r_id,有没有办法做到这一点? INSERT INTO tablec (obj1, action, obj2) (select b.r_id, a.rlt, b.r_id FROM tablea join tableb ON a.obj1 = b.r_obj)
  • @Nataly 不确定我是否完全理解你,但如果我理解了,听起来你需要另一个 join。请参阅我编辑的答案。
  • 不幸的是,这是我最终尝试的,但 db2 不允许这样做。
【解决方案2】:

我不得不使用一种变通方法,因为 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)

然后我使用一个插入语句根据 tablea 中的 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 2023-03-14
    • 2012-12-15
    • 1970-01-01
    相关资源
    最近更新 更多