Last Updated: February 25, 2016
·
7.935K
· dsci

MySQL - Insert stuff from one table to another if entry not exists

It may be some basic MySQL stuff, but it's like every thing - if you're not doing something on a regular basis, some handcraft becomes a bit rusty.

Recently I had to migrate parts of data from one table into another as I changed my db design a bit. I need that as part of a Rake task and it comes in very handy to do this with pure SQL.

I have two tables:

  • networks
  • network_charges

which builds a belongsto association. The data I have to migrate to networkcharges partly exists in networks, but items in networks acts as single inheritance, so I would maybe have multiple WHERE's.

This solution to copy data from one table to the other if a record isn't already copied over works for me:

INSERT INTO network_charges (power_network_id, ap, gp, measuring_and_billing)
SELECT  network_id,
        ap,
        gp,
        measuring_and_billing 
FROM    networks
WHERE type='PowerNetwork'
AND network_id NOT IN (
    SELECT power_network_id 
        FROM network_charges
)

There may be better solutions but I guess using the AND operator to have the exclusions is okay to use.