首页 > 解决方案 > 使用逗号作为分隔符将列拆分为 2 个 clomun

问题描述

我有桌子listings

location (Primary Key)

Chicago, USA
New York, USA
Paris, France

格式严格

City, Country

如同:

<City><comma><single_space><Country>

我想要 2 列location(使用逗号作为分隔符)作为:

city      country

Chicago   USA
New York  USA
Paris     France

标签: mysqlsqlselectsql-update

解决方案


在 MySQL 中,您可以使用substring_index()

select 
    location,
    substring_index(location, ', ', 1) city, 
    substring_index(location, ', ', -1) country
from listings 

DB Fiddle 上的演示

位置 | 城市| 国家
:------------ | :------- | :------
美国芝加哥 | 芝加哥 | 美国    
美国纽约 | 纽约 | 美国    
法国巴黎 | 巴黎 | 法国

如果你想要一个update声明:

update listings
set 
    city = substring_index(location, ', ', 1), 
    country = substring_index(location, ', ', -1)

推荐阅读