【问题标题】:Update same column with multiple values at different positions using Overlay function in Postgres使用 Postgres 中的 Overlay 函数在不同位置使用多个值更新同一列
【发布时间】:2020-10-01 15:36:18
【问题描述】:

我在表test 中有两列,如下所示。我想使用“K”更新消息中的第二个位置,将第四个位置更新为“N”,其中id = 1 使用覆盖功能。我可以根据以下查询更新第二个位置,但无法找到第四个位置的解决方案。

您能给我一些指导吗?谢谢。

test

    id | message
    ------------
    1  | ABCD
    2  | PQRS

我写了下面的查询:

update test
set message = overlay(message placing 'K' from 2 for 1)
where id = 1

我得到了Postgres String Functions and Operators的参考

【问题讨论】:

    标签: sql string postgresql sql-update overlay


    【解决方案1】:

    如果你想用overlay()来做这个,你需要调用它两次:

    overlay(overlay('ABCD' placing 'K' from 2 for 1) placing 'N' from 4 for 1)
    

    你也可以使用substring():

    substring(message, 1, 1) || 'K' || substr(message, 3, 1) || 'N' 
    

    或者,如果message 可以包含超过 4 个字符:

    substring(message, 1, 1) || 'K' || substr(message, 3, 1) || 'N' || substr(message, 5)
    

    最后:一个更简洁的选项(虽然可能效率较低)使用正则表达式:

    regexp_replace(message, '^(.)(?:.)(.)(?:.)', '\1K\2N')
    

    【讨论】:

      猜你喜欢
      • 2019-06-06
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-31
      • 1970-01-01
      相关资源
      最近更新 更多