【问题标题】:How to find the starting position of the last word from the string in PostgreSQL如何从PostgreSQL中的字符串中找到最后一个单词的起始位置
【发布时间】:2021-12-23 20:03:23
【问题描述】:

以下 Oracle 代码的 Postgres 等效项是什么。

Select instr('abc de fgh',' ', -1) from dual;

返回:7

原码:substr(country, instr(country,' ', -1)+1);

我想在 Postgres 中创建相同的逻辑,但位置和反转功能不起作用

【问题讨论】:

  • 您使用的是哪个 Postgres 版本?

标签: sql postgresql substring


【解决方案1】:

既然你提到REVERSE,你可以使用:

SELECT RIGHT(value, POSITION(' ' in REVERSE(value)) - 1) AS country,
       LENGTH(value) - POSITION(' ' in REVERSE(value)) + 1 AS pos
FROM   (SELECT 'abc de fgh' AS value) v;

哪些输出:

country pos
fgh 7

db小提琴here

【讨论】:

    【解决方案2】:

    您显然想要字符串中的最后一个元素,其中元素由空格字符分隔。

    如果您使用的是 Postgres 14,则可以使用:

    split_part('abc de fgh', ' ', -1);
    

    返回fgh

    或带有列引用:split_part(country, ' ', -1)

    在早期版本中,split_part() 不允许负偏移,因此您需要一些不同的东西:

    (string_to_array('abc de fgh', ' '))[cardinality(string_to_array('abc de fgh', ' '))] 
    

    使用列引用会更短一些:

    (string_to_array(country, ' '))[cardinality(string_to_array(country, ' '))] 
    

    这首先将字符串转换为数组,然后选择数组的最后一个元素(这又是使用返回数组长度的cardinality() 函数确定的)

    【讨论】:

    • 我答案中的代码与substr(country, instr(country,' ', -1)+1)相同
    • 感谢您的帮助!
    • 您能否告诉 Oracle 的代码是什么。 substr(country, 1, instr(country,' ', -1)-1) 你能详细说明如何使用这个基数函数吗?
    猜你喜欢
    • 2013-01-04
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 2010-09-12
    相关资源
    最近更新 更多