如何在Postgres中获取空格之前的所有字符串?

3

基本上我需要获取邮政编码字符串中空格之前的部分。

我的当前查询是:

select postcode, left(postcode, length(postcode) - strpos(' ', postcode)) 
from postcodetable

但是它不能正确地返回邮政编码,例如: 第一列是NW1 1AA,第二列应该只是NW1,但实际上它只是重复了第一列。

2个回答

10

您对 strpos() 的参数顺序是错误的。因此,您可以这样做:

select postcode, left(postcode, length(postcode) - strpos(postcode, ' '))
from (values ('NW1 1AA')) v(postcode);

你也可以使用带有正则表达式的 substring() 来完成这个操作:

select postcode, substring(postcode from '[^ ]+'::text)

哦,现在有点好使了,但还是有些问题,我的字符串“WC1B 4HH”被截断成了“WC1”,而不是“WC1B”。使用你的第二个选项,它正常工作了。 - undefined

3
不仅是在 strpos 函数中,参数顺序可能需要颠倒,而且 left 函数的第二个参数也是要从左边选取的字符数。
参考官方 postgres 文档:

left(str text, n int)

返回字符串中前 n 个字符。当 n 为负数时,返回除了最后 |n| 个字符以外的所有字符。

因此正确的查询应该是:
select postcode, left(postcode, strpos(postcode, ' ')) from postcodetable

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