Advertisement
cyclingzealot

Migrating from old IDs to new IDs

Mar 21st, 2014
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 1.40 KB | None | 0 0
  1. ### Create migration lookup table
  2. CREATE TABLE oldCat_to_newCat (oldCatId tinyint not null UNIQUE, newCatId tinyint not null, constraint UNIQUE uniqueCombo (oldCatId, newCatId));
  3.  
  4.  
  5. ### Create Test table to migrate
  6.  
  7. mysql> create table tableToMigrate (catId tinyint not null, catName varchar(20) not null);
  8. Query OK, 0 rows affected (0.11 sec)
  9.  
  10.  
  11. ### Populate tables
  12.  
  13. mysql> insert into tableToMigrate VALUES (1, 'OneToTwo'), (2, 'TwoToOne'), (3, 'ThreeToTwo'), (4, 'FourToFour'), (5, 'FiveToTwo');
  14. Query OK, 5 rows affected (0.00 sec)
  15. Records: 5  Duplicates: 0  Warnings: 0
  16.  
  17.  
  18. mysql> insert into oldCat_to_newCat VALUES (1,2), (2,1), (3,2), (4,4), (5,2);
  19. Query OK, 5 rows affected (0.00 sec)
  20. Records: 5  Duplicates: 0  Warnings: 0
  21.  
  22.  
  23.  
  24. ### Now lets execute the switch with an update and a joining of tables
  25.  
  26.  
  27. mysql> update tableToMigrate tm, oldCat_to_newCat lookup set tm.catId = lookup.newCatId where tm.catId = lookup.oldCatId;
  28. Query OK, 4 rows affected (0.00 sec)
  29. Rows matched: 5  Changed: 4  Warnings: 0
  30.  
  31.  
  32. #### Cool!  We have 5 rows match and MySQL even detects that one row (catId 4) did not change IDs.
  33.  
  34. mysql> select * from tableToMigrate;
  35. +-------+------------+
  36. | catId | catName    |
  37. +-------+------------+
  38. |     2 | OneToTwo   |
  39. |     1 | TwoToOne   |
  40. |     2 | ThreeToTwo |
  41. |     4 | FourToFour |
  42. |     2 | FiveToTwo  |
  43. +-------+------------+
  44. 5 rows in set (0.00 sec)
  45.  
  46.  
  47.  
  48. ### Voilà!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement