[英]PostgreSQL get last value in a comma separated list of values
In a PostgreSQL table I have a column which has values like 在PostgreSQL表中,我有一列,其值类似于
AX,B,C
A,BD
X,Y
J,K,L,M,N
In short , it will have a few comma separated strings in the column for each record. 简而言之,每条记录的列中都会有一些逗号分隔的字符串。 I wanted to get the last one in each record.
我想获得每个记录中的最后一个。 I ended up with this.
我结束了这个。
select id, reverse(substr(reverse(mycolumn),1,position(',' in reverse(mycolumn)))) from mytable order by id ;
Is there an easier way? 有更容易的方法吗?
With regexp_replace
: 使用
regexp_replace
:
select id, regexp_replace(mycolumn, '.*,', '')
from mytable
order by id;
我会这样:
select reverse(split_part(reverse(myColumn), ',', 1))
Is there an easier way?
有更容易的方法吗?
With your current data, Gordon's answer works best imo. 使用当前数据,Gordon的答案最适合imo。 Other options would be a regex (messy), or converting the column to a text[] array eg
('{' || col || '}')::text[]
or variations thereof. 其他选项将是正则表达式(混乱),或将列转换为text []数组,例如
('{' || col || '}')::text[]
或其变体。
If you were using a text[] array instead of plain text for your column, you'd want to use array functions directly: 如果您在列中使用text []数组而不是纯文本,则需要直接使用数组函数:
select col[array_length(col, 1)]
http://www.postgresql.org/docs/current/static/functions-array.html http://www.postgresql.org/docs/current/static/functions-array.html
Example with dummy data: 虚拟数据示例:
with bar as (
select '{a,b,c}'::text[] as foo
)
select foo[array_length(foo, 1)] from bar;
You could, of course, also create a parse_csv()
function or get_last_csv_value()
function to avoid writing the above. 当然,您也可以创建
parse_csv()
函数或get_last_csv_value()
函数来避免编写上述内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.