[英]Postgresql how to update a column if a string has a word in it?
我有2张桌子:
表A的邮政编码列每行有一个邮政编码(示例行:E1 8NF)
表格B,其中的邮政编码列包含多个用逗号分隔的邮政编码(示例行:E1 8NF,E1 8NG,E1 8NJ)
如果表B中存在表A的邮政编码,我想给它一个1
如何在PostgreSQL中做到这一点? 到目前为止我的查询
UPDATE tablea
set pcd = 1 where tablea.postcode exists in tableb.postcode ??
将列表存储在逗号分隔的字段中确实是一个坏主意。 在诸如Postgres之类的具有非常合理的替代方案(如数组和JSON字段)的数据库中,情况甚至更糟。 但是,有时我们会陷入别人的错误决定中。
一种方法是:
update tablea a
set pcd = 1
where exists (select 1
from tableb b
where ',' || a.postcode || ',' like ',' || replace(b.postcodes, ', ', ',') || ','
);
您可以将逗号分隔的列表转换为数组,然后在子选择中使用该列表:
update tablea a
set pcd = 1
where exists (select *
from tableb b
where a.postcode = any(string_to_array(b.postcodes, ','))
);
如果值在逗号之间用空格存储,则需要应用trim()
,如果在更新中加入连接,可能会更容易:
update tablea a
set pcd = 1
from (
select trim(x.pc) as pc
from tableb b,
unnest(string_to_array(b.postcodes)) as x(px)
) t
where a.postcode = t.pc;
尝试这种方式:
UPDATE tablea set pcd = 1 where postcode in (select b.postcode from tableb);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.