2011-09-05 77 views
2

我在我的數據庫中包含街道和房屋號碼的字段。我想在新的專欄中分割房子號碼。我可以通過類似SQL拆分字符串首次發生的一個數字

INSERT INTO mytable(housenumber) VALUES SELECT ??? FROM mytable ? 
+0

那我的地址 - 1,A棟,街,鎮 - (並且有一座B樓,我剛剛有一個網絡表單,爲我提供了兩個單位可供選擇)您希望建築物去哪裏? – Mark

+0

你的字段是如何格式化的,在街道和門牌號碼之間是否有逗號或其他內容? – mslliviu

+0

我的db只包含德文格式的地址,意思是 markus

回答

3

最簡單的解決方案似乎使用substring function with regular expressions。我希望你的PostgreSQL版本支持他們。

SELECT adres, 
     substring(adres from '^.*?(?=[0-9]|$)') AS street, 
     substring(adres from '[0-9].*$') AS housenum 
    FROM mytable; 
 adres  | street | housenum 
-----------------+--------------+----------------- 
some string 12 | some string | 12 
another 2c  | another  | 2c 
no number  | no number | 
99 first number |    | 99 first number 
withnumber1 234 | withnumber | 1 234 
(5 rows) 

由於在評論中提到NullUserException,在街道名稱中可能含有一些本身,這不應該被視爲一個門牌號碼。在這種情況下,我猜想「房屋號碼」可能被定義爲以數字開頭的子字符串,前面是空格。

正則表達式會在這種情況下,這樣看:

SELECT adres, 
     substring(adres from '^.*?(?=\\s[0-9]|$)') AS street, 
     substring(adres from '\\s([0-9].*)$') AS housenum 
    FROM mytable; 

的例子將會再拆不同:

 adres  | street  | housenum 
-----------------+-----------------+----------- 
some string 12 | some string  | 12 
another 2c  | another   | 2c 
no number  | no number  | 
99 first number | 99 first number | 
withnumber1 234 | withnumber1  | 234 
(5 rows) 
+2

如果街道包含一個數字,該怎麼辦? – NullUserException

+0

然後問題必須以不同的方式定義。我會說「在一些空白之後直接拆分第一個數字」。讓我們看看我是否可以爲此做一些正則表達式。;-) – Arsen7