【问题标题】:Update table based on combination of all columns根据所有列的组合更新表
【发布时间】:2018-03-17 09:02:15
【问题描述】:

我正在尝试根据所有列的组合更新更新列。

表 A

NUM_1 NUM_2 NUM_3 Name
----- ----- ----- ---- 
    1     4     6 Test1
    4     4     5 Test2
    4     4     3 Test3

表 B

NUM_1 NUM_2 NUM_3 Name
----- ----- ----- ---- 
    1     4     6 Final_1
    4     4     5 Final_2
    4     4     3 Final_3

如果三列 NUM1,NUM2,NUM 3 匹配,那么我需要使用表 B 中的值更新表 A 中的名称。

有没有使用任何相关查询或其他东西的简单脚本?

【问题讨论】:

  • 你能分享一下你的表结构,并更详细地解释问题吗?

标签: sql oracle plsql


【解决方案1】:

另一种选择:

SQL> select * From a;

      NUM1       NUM2       NUM3 NAME
---------- ---------- ---------- --------------------
         1          4          6 test1      --> according to table B data, this
         4          4          5 test2      --> and this NAME should be updated
         4          4          0 test3
         1          2          3 test4

SQL> select * From b;

      NUM1       NUM2       NUM3 NAME
---------- ---------- ---------- --------------------
         1          4          6 final1
         4          4          5 final2
         4          4          3 final3

SQL> update a set
  2    a.name = (select b.name from b
  3              where b.num1 = a.num1
  4                and b.num2 = a.num2
  5                and b.num3 = a.num3
  6             )
  7  where exists (select null from b
  8                where b.num1 = a.num1
  9                  and b.num2 = a.num2
 10                  and b.num3 = a.num3
 11               );

2 rows updated.

SQL>
SQL> select * From a;

      NUM1       NUM2       NUM3 NAME
---------- ---------- ---------- --------------------
         1          4          6 final1
         4          4          5 final2
         4          4          0 test3
         1          2          3 test4

SQL>

【讨论】:

    【解决方案2】:

    Oracle 不支持用于更新的 ANSI 92 连接,这会使这很容易,但我们可以通过 MERGE 实现相同的目标。

    merge into tableA a
    using ( select * from tableB ) b
    on ( a.num1 = b.num1
         and a.num2 = b.num2
         and a.num3 = b.num3)
    when matched then
        update
        set a.name = b.name
    /
    

    注意:此解决方案假定 (num1, num2, num3)tableB 上的唯一键。但是任何解决方案都需要这种唯一性(否则你怎么知道name 的哪个实例应用于tableA?)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 2010-10-22
      相关资源
      最近更新 更多