简体   繁体   中英

insert data from old table to new table

I have two database table.Two table have same structure. Now i want to insert data from old table to new table if data already exists it will update the old data otherwise insert new. I want to insert or update data by matching some column field value. Any help?

You can make use of ON DUPLICATE KEY UPDATE feature of MySQL. From MySQL doc -

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row.

So, if you have keys defined in the tables you can use this feature. For example, your statement will look like -

insert into target_table (col1, col2, ...) 
select col1, col2,... from source_table
on duplicate key update
  col1 = values(col1),
  col2 = values(col2),

The Best way is you can use the left outer join concept.That will be easy.

    INSERT INTO table1
    (col_1, col_2, col_3, col_4, col_5) values("","","","")
SELECT
    table2_col_1,
    table2_col_2,
    table2_col_3,
    table2_col_4,
    1
FROM
    table_2 AS t2
LEFT OUTER JOIN
    table1 AS t1
ON
    t1.col_1 = t2.table2_col_1;

UPDATE table_2 
SET table2_col_1 = 'value'// here is the value that you need to  implement
WHERE t1.col_1=t2.table2_col_1;//here is your condition

From your Question , i understood that your table2 is not that much important. So you can drop the values present in the entire table2 ,so that the structure will not get affected.After that was finished.. you can just export the insert query to implement the values that is present in the table1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM