Search code examples
mysqlmultiple-columnscopyingexact-match

Copying One column from table to another table that has matching variables in another column


I hope I can explain this to make sense lol.

I am trying to copy variables from one hats_old.red to hats_new.red that match hats_new.name in both tables, if they do not match then i need it to do nothing so it does not null the value or set it to 0.

This is as far as ive gotten. This changes unmatched to 0 which i am trying to avoid and cannot figure the rest out. This is for Mysql

Thank you

UPDATE hats_new 
SET hats_new.red = (
    SELECT hats_old.red
    FROM hats_old
    WHERE hats_old.name = hats_new.name LIMIT 1
);

Solution

  • An update with a join should do the trick:

    UPDATE hats_new hn
    JOIN   hats_old ho ON hn.name = oh.name
    SET    hn.red = ho.red