如何将字符串拆分为两个新属性

时间:2016-04-02 03:47:08

标签: sql string postgresql

我的字符串数据的值看起来像'Washington, DC',其中City,State存储在名为venue_city_state的表属性中。

我试图将此属性拆分为另外两个名为venue_city和venue_state的属性,但是当我这样做时

UPDATE all_event_details 
SET venue_city = i.venue_city, venue_state = i.venue_state
FROM (SELECT split_part(venue_city_state, ',', 1) AS venue_city, 
  split_part(venue_city_state, ',', 2) AS venue_state 
  FROM all_event_details) i;

我只在场地城市获得华盛顿州的第一个值,并且在我的桌子行的所有的场地状态中获得DC。不是该特定行的venue_city_state中的值。

如何更改此更新以将venue_city和venue_state从每个行的venue_city_state中取出而不仅仅是表格中的第一个行?

任何和所有帮助表示赞赏!感谢

2 个答案:

答案 0 :(得分:1)

无需进行子选择:

UPDATE all_event_details 
    SET venue_city = split_part(venue_city_state, ',', 1), 
        venue_state = split_part(venue_city_state, ',', 2)

答案 1 :(得分:0)

已经有a_horse_with_no_name的答案,它更好,但您可以通过添加WHERE子句来匹配all_event_details中的每一行与辅助选择中相应的行来实现您的目的。

 UPDATE all_event_details 
 SET venue_city = i.venue_city, venue_state = i.venue_state
 FROM (SELECT id,
              split_part(venue_city_state, ',', 1) AS venue_city, 
              split_part(venue_city_state, ',', 2) AS venue_state 
       FROM all_event_details) i
 WHERE id = i.id;

我假设id是all_event_details键。