Pregunta

I'm trying to update TableA with records from TableB but only where there are no records in TableA already existing with the same Name Column value. I have queries that will do that however what I'd like to do is in the cases where a 'matched' record exists but does not have values in Fieldx/y/z the existing record will update. For instance:

  • Target Table | Bob | NULL | NULL|
  • Source Table | Bob | New York | Doctor

The Target table would not have a new record created since 'Bob' exists but that existing record would have New York and Doctor added since those fields are NULL or empty/

¿Fue útil?

Solución

You can do this with the on duplicate key update option to insert. First create a unique index on name, so duplicates are not allowed:

create unique index TargetTable_name on TargetTable(name);

Then:

insert into TargetTable(name, col1, col2)
    select name, col1, col2
    from SourceTable
    on duplicate key update col1 = coalesce(TargetTable.col1, values(col1)),
                            col2 = coalesce(TargetTable.col2, values(col2));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top