Postgres 数据库表在 char(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
可以用什么表达式来代替 of ?标记来产生这个。可以使用一些正则表达式或其他解决方案吗?
使用 PostgreSQL 9.1.2
最佳答案
将值转换为数组并使用它:
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;
在 Postgres 9.6 中,支持这种简写:
select (string_to_array(t, ' '))[1] as first_word,
(string_to_array(t, ' '))[2:]
from test;
关于sql - 如何在postgres中提取第一个和剩余的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45785188/