Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL, Copy selected fields from one table to another

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

like image 499
ix3 Avatar asked Jun 23 '12 09:06

ix3


People also ask

How do I copy data from one table to another table in MySQL?

Copy a table from one database to another. In MySQL, the easiest way to copy a table with its data between two databases is to use the CREATE TABLE AS statement, but note, that you need to provide the target database name as a table prefix. CREATE TABLE new-database-name. new-table-name AS SELECT * FROM old-database.

How can insert selected columns from one table to another in MySQL?

SELECT statement provides an easy way to insert rows into a table from another table. If you want to copy data from one table to another in the same database, use INSERT INTO SELECT statement in MySQL.

How do you copy data from one column in a table to another column in another table?

Click the tab for the table with the columns you want to copy and select those columns. From the Edit menu, click Copy. Click the tab for the table into which you want to copy the columns. Select the column you want to follow the inserted columns and, from the Edit menu, click Paste.

How do I copy data from one table to another table in SQL?

The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.


1 Answers

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.

like image 190
Andriy M Avatar answered Sep 30 '22 16:09

Andriy M