Search code examples
mysqlreplaceduplicatesuniqueskip

Replace only duplicates and skip unique


I have this simple table: (ID is unique key)

-----------------------------
-   ID   ----    NAME    ----
-----------------------------
-   1    ----    Peter   ----
-   2    ----   Suzanne  ----
-   3    ----   Thomas   ----
-----------------------------

and I want to insert these table data into table using query:

-----------------------------
-   ID   ----    NAME    ----
-----------------------------
-   2    ----    Alex    ----
-   4    ----    Eric    ----
-   5    ----    Paul    ----
-----------------------------

and what I want is, that data from new table will replace old data and entries, which don't exist in old table get skipped.

So final table will look like this:

-----------------------------
-   ID   ----    NAME    ----
-----------------------------
-   1    ----    Peter   ----
-   2    ----    Alex    ----
-   3    ----   Thomas   ----
-----------------------------

only line with ID 2 got replaced, lines with IDs 4,5 got skipped, because didn't exist in old table.

Is that possible? Thanks


Solution

  • You seem to want an update:

    update table1 t1 join
           table2 t2
           on t1.id = t2.id
        set t1.name = t2.name;