gpt4 book ai didi

python - Postgres 更新表 -> 更改 text[] 中的子字符串

转载 作者:行者123 更新时间:2023-11-29 12:15:51 25 4
gpt4 key购买 nike

我正在使用 Python、SQLAlchemy(我不使用 ORM)和 Postgres。我在 Postgres 中有一个表,其中包括两个文本 [] 字段(到和从)和其他一些(不相关)。如果“from”列包含子字符串“priority”,则“to”列可能包含子字符串“head”。如果是这样,我想将其更改为“尾部”。或者,我也很高兴有一个解决方案,可以更改整个“至”文本 [] 列。

表格:从文本[]到文本[]

到目前为止我做了什么:

eng = engine.execute("select to from table, unnest(from) f where f like (%s);", ('%priority%'))

for row in eng:
if row[0][0].find('head'):
row[0][0].replace('head', 'tail')

现在,我不知道如何进行更新

我试过:

#this only updates it, but if the next time I do the first query it's still the same(I know it's because it's only a select statement. I just included it if it might be helpful somehow)
engine.execute('SELECT regexp_replace(to::varchar, %s, %s) from table, 'head', 'tail');

然后我尝试了:

engine.execute("update table set to = (%s) WHERE to = (%s)", 'head', 'tail')

如果 UPDATE 语句还包含“from”需要包含“priority”的条件,那可能是最好的。

非常感谢任何帮助。

最佳答案

你可以单独使用sql来解决整个问题。给你:

update table
-- replace head by tail in the to-array
set to = array_replace(to, 'head', 'tail')
where ARRAY['priority'] <@ from
and ARRAY['head'] <@ to

注意1:可能你需要用“”包裹你的名字(table,from,to),因为它们是sql中的保留关键字。

update "table"
set "to" = array_replace("to", 'head', 'tail')
where ARRAY['priority'] <@ "from"
and ARRAY['head'] <@ "to"

注意 2:<@ 表示“包含于”,参见 https://www.postgresql.org/docs/current/functions-array.html .

关于python - Postgres 更新表 -> 更改 text[] 中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54966774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com