update one table with data from another

后端 未结 5 676
孤独总比滥情好
孤独总比滥情好 2020-11-27 02:36

Table 1:

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

Table 2:

id    na         


        
相关标签:
5条回答
  • 2020-11-27 03:03

    Try following code. It is working for me....

    UPDATE TableOne 
    SET 
    field1 =(SELECT TableTwo.field1 FROM TableTwo WHERE TableOne.id=TableTwo.id),
    field2 =(SELECT TableTwo.field2 FROM TableTwo WHERE TableOne.id=TableTwo.id)
    WHERE TableOne.id = (SELECT  TableTwo.id 
                                 FROM   TableTwo 
                                 WHERE  TableOne.id = TableTwo.id) 
    
    0 讨论(0)
  • 2020-11-27 03:09

    Oracle 11g R2:

    create table table1 (
      id number,
      name varchar2(10),
      desc_ varchar2(10)
    );
    
    create table table2 (
      id number,
      name varchar2(10),
      desc_ varchar2(10)
    );
    
    insert into table1 values(1, 'a', 'abc');
    insert into table1 values(2, 'b', 'def');
    insert into table1 values(3, 'c', 'ghi');
    
    insert into table2 values(1, 'x', '123');
    insert into table2 values(2, 'y', '456');
    
    merge into table1 t1
    using (select * from table2) t2
    on (t1.id = t2.id)
    when matched then update set t1.name = t2.name, t1.desc_ = t2.desc_;
    
    select * from table1;
    
            ID NAME       DESC_
    ---------- ---------- ----------
             1 x          123
             2 y          456
             3 c          ghi
    

    See also Oracle - Update statement with inner join.

    0 讨论(0)
  • 2020-11-27 03:14

    For MySql:

    UPDATE table1 JOIN table2 
        ON table1.id = table2.id
    SET table1.name = table2.name,
        table1.`desc` = table2.`desc`
    

    For Sql Server:

    UPDATE   table1
    SET table1.name = table2.name,
        table1.[desc] = table2.[desc]
    FROM table1 JOIN table2 
       ON table1.id = table2.id
    
    0 讨论(0)
  • 2020-11-27 03:24
    UPDATE table1
    SET 
    `ID` = (SELECT table2.id FROM table2 WHERE table1.`name`=table2.`name`)
    
    0 讨论(0)
  • 2020-11-27 03:25

    Use the following block of query to update Table1 with Table2 based on ID:

    UPDATE Table1, Table2 
    SET Table1.DataColumn= Table2.DataColumn
    where Table1.ID= Table2.ID;
    

    This is the easiest and fastest way to tackle this problem.

    0 讨论(0)
提交回复
热议问题