【问题标题】:Split column in 2 clomuns using comma as seperator使用逗号作为分隔符将列拆分为 2 列
【发布时间】:2020-04-04 18:19:30
【问题描述】:

我有桌子listings:

location (Primary Key)

Chicago, USA
New York, USA
Paris, France

格式严格

City, Country

同:

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

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

city      country

Chicago   USA
New York  USA
Paris     France

【问题讨论】:

    标签: mysql sql select sql-update


    【解决方案1】:

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

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

    Demo on DB Fiddle

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

    如果您想要update 声明:

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

    【讨论】:

    • 好的,我现在试试
    • 抱歉,我忘了说,我必须在 City 和 Country 列中插入值。我的坏
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多