Postgres:限制返回字符串的长度,但需要以完整单词结尾。

4

我正在使用Postgres尝试在返回字符串之前截断它,以便可以在客户端部分结果列表中显示。关键是它需要以完整的单词结尾。我已经做到了这一点: SELECT comments, substr(comments, 1, 80) AS "trunc" FROM book; 下一步应该是对子字符串进行正则表达式的子字符串操作(也许要确保字符串以空格结尾)吗?

1个回答

6
使用substring(string from pattern)函数。示例:提取12个字符。
with the_data(comments) as (
    values
        ('follow me'::text),
        ('abcdef ghijkl'),
        ('abcd efgh ijkl'),
        ('abc def ghi jkl'),
        ('ab cd ef gh ij kl')
    )

select substring(left(comments || ' ', 12) from '.*\s')
from the_data;

  substring   
--------------
 follow me 
 abcdef 
 abcd efgh 
 abc def ghi 
 ab cd ef gh 
(5 rows)

如果您添加此示例 ('follow me'::text) - 它会截断 'me',但我对 OPs 问题的解释是它应该返回 'follow me'(在此示例中)。 - Nick
如果您只是在“comments”值后添加了一个空格,似乎可以解决它:select substring(left(comments || ' ', 12) from '.*\s') from the_data; - Nick
实际上,它结束的单词并不重要,只要它是一个完整的单词即可。 - eabates
是的 - 这是一个很好的答案。+1 - Nick
非常感谢klin和@Nicarus。 - eabates

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接