获取一个Postgres数组的最后一个元素,以声明 [英] Getting the last element of a Postgres array, declaratively

查看:727
本文介绍了获取一个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天全站免登陆