【问题标题】:How to update a column using another column's multiple data?如何使用另一列的多个数据更新一列?
【发布时间】:2018-09-16 04:22:39
【问题描述】:

测试1

t1  t2

1   

测试2

x

1

2

3

upto 20

所以我希望将所有 x 值复制到 t2
我该怎么办?

更详细:

有 2 个表 'test1' , 'test2'。 ' test1 ' 有 2 列,即 ' t1 ' , ' t2 ' 和 ' test2 ' 有 1 列,即 ' x '。所以我需要 将 test2.x 列值复制到 test1.t2 列。测试1.t1 - 1,测试1.t2 - null, test2.x - 1,2,3,4 ..... 20

【问题讨论】:

  • 你的问题我不清楚
  • 对这个问题的含糊之处投反对票。请考虑重新措辞...
  • test1.t1 1,2,3 ... 20 的值,也是..?
  • 有 2 个表 'test1' , 'test2'。 “test1”有 2 列,即“t1”、“t2”和“test2”有 1 列,即“x”。所以我需要将 test2.x 列值复制到 test1.t2 列。 test1.t1 - 1, test1.t2 - null, test2.x - 1,2,3,4 ..... 20,希望现在你明白了。

标签: sql oracle oracle11g sql-update sql-merge


【解决方案1】:

问题文本不清楚,据我了解,您的 test1 表的 t1 列的值也为 1,2,3 ... 20,如果您想从 test2.x 中复制所有内容,您可以使用:

update test1 t1
   set t1.t2 = ( select t2.x
                   from test2 t2
                  where t2.x = t1.t1 );

但是,实际上不需要另一个表(table2)

update test1 t1 set t1.t2 = t1.t2;

关于您上次的编辑,您需要一个merge 声明:

merge into test1 a
  using test2 b
    on (nvl(a.t1,0) = nvl(b.x,0))
  when matched then
    update set a.t2 = nvl(b.x,0)
  when not matched then
    insert(t2)
    values(nvl(b.x,0));

然后你可以得到以下内容:

select * from test1 order by t2;

T1  T2
--  --------------------------------------------------
1   1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    .
    .
    .
    20

demo

【讨论】:

  • 感谢您的回答,但我已经尝试过了,它只会更新 test1 表的一行,我希望 test1 中有 1,2,3 ..... 20。 t2 列。希望你能理解我的问题。我需要将 test2.x 值复制到 test1.t2 列。
  • @Ranjan 不客气,朋友。我已经编辑了您的问题(根据您的评论)和我的回答。
  • 谢谢@Barbaros Ozhan,我很欣赏你的回答,但是如果我需要的值应该与 test2.x 完全一样,而不是并排,应该逐行。就像你的第一个答案一样。没关系,但它只更新 1 行,我需要 'test1' 表中的所有 20 行。
  • update (select * from test1,test2) set t2=x;我在此查询中遇到错误。(ORA-01779:无法修改映射到非键保留表的列。)
  • @Ranjan 我编辑了答案,以便您可以在演示中看到结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多