如果存在子地址(例如单元号),是否可以拆分地址列?

时间:2019-05-30 06:14:18

标签: mysql

我的一个表中的一列中列出了地址,其格式如下(地址编号已在另一列中)。

addressStreet
-----------------
S 1ST ST UNIT A
S 1ST ST UNIT 101
Main AVE H2
Brooklyn BLVD
Brooklyn BLVD 104

我正在尝试找出将子地址(UNIT#,ETC ..)分成第二列的最佳方法。

我希望看到

addressStreet       subStreet
--------------      ------------
S 1ST ST            UNIT A
S 1ST ST            UNIT 101
Main AVE            H2
Brooklyn BLVD
Brooklyn BLVD       104

在此问题上,感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:1)

好吧,由于表中的地址数据没有特定的定界符,因此如果像AVE,RD,ST,BLVD这样的标签很少,则可以在mysql中使用substring_index来实现,如下所示:

 select
     case when address like '% AVE%' then concat(substring_index(address,' AVE', 1), ' AVE')
          when address like '% ST%' then concat(substring_index(address,' ST', 1), ' ST')
          when address like '% RD%' then concat(substring_index(address,' RD', 1), ' RD')
          when address like '% BLVD%' then concat(substring_index(address,' BLVD', 1),' BLVD')  
     end as addressStreet,
     coalesce(case when address like '%AVE %' then substring_index(address,' AVE', -1)
          when address like '%ST %' then substring_index(address,' ST', -1)
          when address like '%RD %' then substring_index(address,' RD', -1)
          when address like '%BLVD %' then substring_index(address,' BLVD', -1)  
     end,'') as subStreet
 from
     street;
+---------------+-----------+
| addressStreet | subStreet |
+---------------+-----------+
| S 1ST ST      |  UNIT A   |
| S 1ST ST      |  UNIT 101 |
| Main AVE      |  H2       |
| Brooklyn BLVD |           |
| Brooklyn BLVD |  104      |
+---------------+-----------+
5 rows in set (0.00 sec)

如果使用PostgreSQL,事情会更容易:

select 
    (regexp_split_to_array(address,' ST| AVE| BLVD| RD'))[1] as address_street,
    (regexp_split_to_array(address,' ST| AVE| BLVD| RD'))[2] as sub_street
from 
    street;;
 address_street | sub_street 
----------------+------------
 S 1ST          |  UNIT A
 S 1ST          |  UNIT 101
 Main           |  H2
 Brooklyn       | 
 Brooklyn       |  104
(5 rows)