update target table based on data source table if empty

Viewed 52

Possibly a duplicate been searching for the specific answer i need but couldnt find it. I have two simple tables

Source :
    | Id | companyName | adress  |
    |----|-------------|---------|
    |  1 | aquatics    | street1 |
    |  2 | rivers      | street2 |

target :
    | Id | nameCompany | companyAdress  |
    |----|-------------|----------------|
    |  1 | aquatics    | street1        |
    |  2 | rivers      |                |

I simplified the matter, I have two sets of data the source table is extern data en i as a dev want to update my table with the extern data.

So we see that in the source everything is filled in. I miss some info. In this case i miss the adress.

How can i run a query that checks: your row is incomplete. Lemme update this target row with the source data.

Only problem is. Extern data uses a different name voor the same columns as i have.

Been a couple of days with mysql. So pls try to explain noob friendly tried some thing but i couldnt figure it out

1 Answers

Below query updates companyAdress on target table if adress column on Source table is not equal to companyAdress on target table.

If you only need to update the empty values for target.companyAdress you should change the condition where s.adress <> t.companyAdress to where t.companyAdress =''

update target t
inner join `Source` s
on t.nameCompany=s.companyName
set t.companyAdress=s.adress
where s.adress <> t.companyAdress ;

Demo: https://www.db-fiddle.com/f/pB6b5xrgPKCivFWcpQHsyE/0

Related