Sql 在postgres中的数组列上使用regexp_replace
我试图使用regexp更新数组列的每个元素中出现的所有值 如果列的类型不是Sql 在postgres中的数组列上使用regexp_replace,sql,regex,postgresql,Sql,Regex,Postgresql,我试图使用regexp更新数组列的每个元素中出现的所有值 如果列的类型不是text[]和text,我将使用此查询更新: UPDATE my_table SET my_column = regexp_replace( my_column, 'foo(\d+)', 'bar\1', 'g' ) 如何替换数组列中的每个元素?使用CTE来unest()数组,对数组元素进行转换并聚合回一个数组,然后用于更新。假设您的表具有主键: WITH changed(key, arr) AS ( SEL
text[]
和text,我将使用此查询更新:
UPDATE my_table
SET my_column = regexp_replace(
my_column, 'foo(\d+)', 'bar\1', 'g'
)
如何替换数组列中的每个元素?使用CTE来unest()
数组,对数组元素进行转换并聚合回一个数组,然后用于更新。假设您的表具有主键:
WITH changed(key, arr) AS (
SELECT id, array_agg(regexp_replace(col, 'foo(\d+)', 'bar\1', 'g'))
FROM my_table, unnest(my_column) un(col)
GROUP BY id
)
UPDATE my_table
SET my_column = arr
FROM changed
WHERE id = key
据我所知,最简单的方法是:
UPDATE my_table SET
my_column = array(
SELECT regexp_replace(unnest(my_column), 'foo(\d+)', 'bar\1', 'g'))
PostgreSQL太聪明了。可以使用SRF(设置返回函数,只需谷歌搜索)作为其他函数的参数。例如:
select abs(unnest('{1,-2,3}'::int[]));
这对我来说是一样的
select abs(x) from unnest('{1,-2,3}'::int[]) as x;
但是更短
它回来了
┌─────┐
│ abs │
╞═════╡
│ 1 │
│ 2 │
│ 3 │
└─────┘
┌─────┐
│ 防抱死制动系统│
╞═════╡
│ 1.│
│ 2.│
│ 3.│
└─────┘
而array(select…
只是将select…
结果转换为数组的数组构造函数