MYSQL, Copy selected fields from one table to another

后端 未结 8 1750
情深已故
情深已故 2020-12-23 09:58

In MySQL, How do I copy a FIELD with all RECORDS from TABLE1 to TABLE2 which corresponds to a primary key ie: EMPLOYEE no.?

相关标签:
8条回答
  • 2020-12-23 10:26
    update
      table1 t1
      join table2 t2 on t2.field = t1.field
    set
      t1.field1 = t2.matchingfield
    where
      t1.whatever = t2.whatever
    
    0 讨论(0)
  • 2020-12-23 10:32

    Suppose if the table structure is as follows.

    TableA - Col1, Col2 ,Col3 TableB - Col1, Col2 ,Col3

    There is no need to select all column of the table to transfer data from 1 table to another table in same databse. You can copy (insert) the rows from TableA to TableB.

    Code as follows -

    Insert into TableB (Col1, Col2 ,Col3)
    Select Col1, Col2 ,Col3 from TableA
    

    You can also do this -

    Insert into TableB (Col1, Col2, Col3) 
    Select * from TableA
    

    Both codes work , you need to see your requirement.

    Generic code -

    INSERT INTO table2 (column1, column2, column3, ...)
    SELECT column1, column2, column3, ...
    FROM table1
    WHERE condition;
    

    You can add 'Where' condition if you need.

    Thank you!!!

    0 讨论(0)
  • 2020-12-23 10:33

    Try this

    INSERT INTO `table2` (`field_name2`) SELECT `field_name` FROM `table1`
    
    0 讨论(0)
  • 2020-12-23 10:34

    You can use this to copy all the records from table1 into table2 with a condition.

    Insert into table2  select  * from table1 where field1=condition
    
    0 讨论(0)
  • 2020-12-23 10:39

    If you mean you want to update one table's column using another table's column, then here are some options:

    1. A join:

      UPDATE table1 AS t1
        INNER JOIN table2 AS t2 ON t1.EmpoyeeNo = t2.EmployeeNo
      SET t1.SomeColumn = t2.SomeColumn
      

      Alternatively it could be a left join:

      UPDATE table1 AS t1
        LEFT JOIN table2 AS t2 ON t1.EmpoyeeNo = t2.EmployeeNo
      SET t1.SomeColumn = t2.SomeColumn
      

      which would essentially empty (set to NULL) the values where no match occurred.

    2. A subquery:

      UPDATE table1
      SET SomeColumn = (
        SELECT SomeColumn
        FROM table2
        WHERE EmployeeNo = table1.EmployeeNo
      )
      

      This is equivalent to the left join solution in #1.

    Note that in all cases it is assumed that a row in table1 can match no more than one row in table2.

    0 讨论(0)
  • 2020-12-23 10:39

    INSERT INTO table_1(column-1, column-2) SELECT column-1, column-2 FROM table_2;

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