简体   繁体   English

如何根据同一表中的另一列数据填充一列?

[英]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... 由于美国邮政编码格式为5位数字(例如12345),而CAN邮政编码的格式类似(例如G5Y 5S7),因此mysql是否可以使用某种形式填充国家/地区数据...

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? 然后返回并使用某种WHERE zip LIKE NULL来用CAN填充其他国家/地区数据?

Thanks 谢谢

You could check the length of the value in the zip column. 您可以在zip列中检查值的长度。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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