Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何提取postgres中的第一个和剩余单词_Sql_Regex_Postgresql - Fatal编程技术网

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

Sql 如何提取postgres中的第一个和剩余单词,sql,regex,postgresql,Sql,Regex,Postgresql,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 firstw

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
什么表达式可以用来代替?标记来生成这个。可以使用一些regexp或其他解决方案吗


使用PostgreSQL 9.1.2将值转换为数组,并使用:

select (string_to_array(t, ' '))[1] as first_word,
       (string_to_array(t, ' '))[2:99]
from test;
数组比字符串更容易使用,尤其是当您在一行中有列表时。但是,如果喜欢使用
array\u to\u string()
,可以将其转换回字符串

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

select (string_to_array(t, ' '))[1] as first_word,
       (string_to_array(t, ' '))[2:cardinality( string_to_array(t, ' ') )]
from test;
在Postgres 9.6中,支持这种速记:

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

我使用测试中的
select(字符串到数组(名称“”)[1],数组到字符串((字符串到数组(名称“”))[2:99],”)将结果转换回字符串这样行吗?@Andrus。是的,很好。