代码之家  ›  专栏  ›  技术社区  ›  Andrus

如何提取postgres中的第一个和剩余单词

  •  2
  • Andrus  · 技术社区  · 8 年前

    Postgres数据库表包含字符(20)列中由空格分隔的单词。 select语句的结果应该是包含两列的表。

    第二列应该包含剩余的单词。

    create temp table test (name char(20)) on commit drop ;
    insert into test values
    ('word11 word12 word13'),
    ('word21'),
    ('word31 word32');
    
    SELECT 
            ? as firstword,
            ? as remainingwords
    from test;
    

    应该产生

    firstword     remainingwords
    word11        word12 word13
    word21
    word31        word32
    

    使用PostgreSQL 9.1.2

    1 回复  |  直到 8 年前
        1
  •  3
  •   Gordon Linoff    8 年前

    将值转换为数组并使用:

    select (string_to_array(t, ' '))[1] as first_word,
           (string_to_array(t, ' '))[2:99]
    from test;
    

    数组比字符串更容易处理,尤其是当一行中有列表时。但是,如果您喜欢使用,可以将其转换回字符串 array_to_string()

    在您的Postgres版本中,这更准确地写为:

    select (string_to_array(t, ' '))[1] as first_word,
           (string_to_array(t, ' '))[2:cardinality( string_to_array(t, ' ') )]
    from test;
    

    select (string_to_array(t, ' '))[1] as first_word,
           (string_to_array(t, ' '))[2:]
    from test;