Oracle SQL: Update a table with data from another table

后端 未结 7 2256
广开言路
广开言路 2020-11-22 02:01

Table 1:

id    name    desc
-----------------------
1     a       abc
2     b       def
3     c       adf

Table 2:

id    na         


        
7条回答
  •  没有蜡笔的小新
    2020-11-22 02:31

    If your table t1 and it's backup t2 have many columns, here's a compact way to do it.

    In addition, my related problem was that only some of the columns were modified and many rows had no edits to these columns, so I wanted to leave those alone - basically restore a subset of columns from a backup of the entire table. If you want to just restore all rows, skip the where clause.

    Of course the simpler way would be to delete and insert as select, but in my case I needed a solution with just updates.

    The trick is that when you do select * from a pair of tables with duplicate column names, the 2nd one will get named _1. So here's what I came up with:

      update (
        select * from t1 join t2 on t2.id = t1.id
        where id in (
          select id from (
            select id, col1, col2, ... from t2
            minus select id, col1, col2, ... from t1
          )
        )
      ) set col1=col1_1, col2=col2_1, ...
    

提交回复
热议问题