Performing a Related-Table Update Using Table Replacement

• Writ e a program t hat uses t he inform at ion from t he city t able t o generat e and execut e UPDATE st at em ent s t hat updat e t he states t able one st at e at a t im e. • Use m ysql t o generat e t he UPDATE st at em ent s.

12.19.4 Performing a Related-Table Update Using Table Replacement

The t able- replacem ent approach works as follows. To ext end t he states t able w it h t he capital and largest colum ns from t he city t able, cr eat e a tmp t able t hat is like t he states t able but adds capital and largest colum ns: CREATE TABLE tmp name VARCHAR30 NOT NULL, state name abbrev CHAR2 NOT NULL, 2-char abbreviation statehood DATE, date of entry into the Union pop BIGINT, population as of 41990 capital VARCHAR30, capital city largest VARCHAR30, most populous city PRIMARY KEY abbrev ; Then populat e tmp using t he result of a j oin bet ween states and city t hat m at ches up rows in t he t wo t ables using st at e nam es: INSERT INTO tmp name, abbrev, statehood, pop, capital, largest SELECT states.name, states.abbrev, states.statehood, states.pop, city.capital, city.largest FROM states LEFT JOIN city ON states.name = city.state; The query uses a LEFT JOIN for a reason. Suppose t he city t able is incom plet e and doesnt cont ain a row for every st at e. I n t hat case, a regular j oin will fail t o produce an out put row for any st at es t hat are m issing from t he city t able, and t he result ing tmp t able w ill be m issing records for t hose st at es, even t hough t hey are present in t he states t able. Not good The LEFT JOIN ensures t hat t he SELECT produces out put for every row in t he states t able, whet her or not it s m at ched by a city t able row. Any st at e t hat is m issing in t he city t able w ould end up w it h NULL values in t he tmp t able for t he capital and largest colum ns, but t hat s appropriat e when you dont know t he cit y nam es—and generat ing an incom plet e row cert ainly is preferable t o losing t he row ent irely. The result ing tmp t able is like t he original one, but has t w o new colum ns, capital and largest. You can exam ine it t o see t his. Aft er verifying t hat youre sat isfied wit h t he tmp t able, use it t o replace t he original states t able: DROP TABLE states; ALTER TABLE tmp RENAME TO states; I f you want t o m ake sure t here is no t im e, however brief, during which t he states t able is unavailable, perform t he replacem ent like t his inst ead: RENAME TABLE states TO states_old, tmp TO states; DROP TABLE states_old;

12.19.5 Performing a Related-Table Update by Writing a Program