|
| 1 | +START TRANSACTION; |
| 2 | + |
| 3 | +-- Step 1: Add latitude and longitude columns to address table |
| 4 | +ALTER TABLE address |
| 5 | + ADD COLUMN latitude DECIMAL(11, 8), |
| 6 | + ADD COLUMN longitude DECIMAL(11, 8); |
| 7 | + |
| 8 | +-- Step 2: Migrate existing lat/long data from charge_box to address table |
| 9 | +-- For charge boxes that already have an address |
| 10 | +UPDATE address a |
| 11 | + INNER JOIN charge_box cb ON a.address_pk = cb.address_pk |
| 12 | + SET a.latitude = cb.location_latitude, |
| 13 | + a.longitude = cb.location_longitude |
| 14 | +WHERE cb.location_latitude IS NOT NULL |
| 15 | + AND cb.location_longitude IS NOT NULL; |
| 16 | + |
| 17 | +-- Step 3a: Create new address rows for charge boxes without an address but with lat/long |
| 18 | +INSERT INTO address (latitude, longitude) |
| 19 | +SELECT location_latitude, location_longitude |
| 20 | +FROM charge_box |
| 21 | +WHERE address_pk IS NULL |
| 22 | + AND location_latitude IS NOT NULL |
| 23 | + AND location_longitude IS NOT NULL; |
| 24 | + |
| 25 | +-- Step 3b: Update charge_box to reference the newly created addresses |
| 26 | +UPDATE charge_box cb |
| 27 | + INNER JOIN address a ON cb.location_latitude = a.latitude |
| 28 | + AND cb.location_longitude = a.longitude |
| 29 | + SET cb.address_pk = a.address_pk |
| 30 | +WHERE cb.address_pk IS NULL |
| 31 | + AND cb.location_latitude IS NOT NULL |
| 32 | + AND cb.location_longitude IS NOT NULL; |
| 33 | + |
| 34 | +-- Step 4: Drop the old columns from charge_box |
| 35 | +ALTER TABLE charge_box |
| 36 | +DROP COLUMN location_latitude, |
| 37 | +DROP COLUMN location_longitude; |
| 38 | + |
| 39 | +COMMIT; |
0 commit comments