简体   繁体   中英

How To Populate One Column Based On Another Columns Data In Same Table?

I have two sets of data I joined into a single table. One was USA addresses and the other was Canadian addresses. I need the option to be able to sort by Country. So I inserted a blank country column into my table and my table now looks like this:

 state | country | zip
-----------------------
       |         | 
       |         |


I have the state and zip data but my country column is empty. Since US zip code format is 5 digits (ex. 12345) and CAN zip are formatted like (ex. G5Y 5S7) is it possible with mysql to populate the country data with some sort of...

UPDATE table 
SET country = US 
WHERE zip (LIKE or =) (US zip format);

And then go back and use some sort of WHERE zip LIKE NULL to populate the rest of country data with CAN?

Thanks

You could check the length of the value in the zip column.

UPDATE table 
   set country = 'US'
 where char_length(zip) = 5;

then:

UPDATE table 
   set country = 'CAN'
 where country is null

-- or, in one go --

UPDATE table t
   set country = 
  (case when char_length(t.zip) = 5
   then 'US'
  else 'CAN'
  end);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM