以声明方式从Postgres字符串中获取最后一个单词 [英] Getting the last word from a Postgres string, declaratively

查看:78
本文介绍了以声明方式从Postgres字符串中获取最后一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该问题的原始标题是以声明方式获取Postgres数组的最后一个元素

如何获取在Postgres中数组的最后一个元素?

How to obtain the last element of the array in Postgres?

我需要声明性地进行操作,因为我想将其用作ORDER BY条件。我不想为此创建特殊的PGSQL函数,在这种情况下,对数据库的更改越少越好。

I need to do it declaratively as I want to use it as a ORDER BY criteria. I wouldn't want to create a special PGSQL function for it, the less changes to the database the better in this case.

事实上,我要做的是按包含多个单词的特定列的最后一个单词排序。更改模型不是这里的选择。

In fact, what I want to do is to sort by the last word of a specific column containing multiple words. Changing the model is not an option here.

换句话说,我要推送Ruby的 sort_by {| x | x.split [-1]} 进入数据库级别。我可以使用Postgres string_to_array regexp_split_to_array 函数将值拆分为单词数组,然后如何获取其最后一个元素?

In other words, I want to push Ruby's sort_by {|x| x.split[-1]} into the database level. I can split a value into array of words with Postgres string_to_array or regexp_split_to_array functions, then how to get its last element?

推荐答案

如果我正确地理解了您的问题,则您有一个字符串,首先要在某个分隔符上将其拆分,然后再查找

If I understand your question correctly you have a string and you're first splitting it on some separator and then afterwards finding the last element of the array and discarding the rest.

您可能会错过中间人并直接获得最后一个元素:

You could miss out the middle man and get the last element directly:

SELECT regexp_replace('foo bar baz', '^.* ', '')

结果:

baz

这篇关于以声明方式从Postgres字符串中获取最后一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆