Postgresql如何在字符串中包含单词时更新列?

Postgresql如何在字符串中包含单词时更新列?,sql,postgresql,Sql,Postgresql,我有两张桌子: 表A的邮政编码列每行有一个邮政编码(示例行:E1 8NF) 表B中有一个邮政编码列,其中多个邮政编码由逗号分隔(示例行:E1 8NF、E1 8NG、E1 8NJ) 如果表A中的邮政编码存在于表B中,我想给它一个1 如何在postgresql中实现这一点?我的问题到目前为止 UPDATE tablea set pcd = 1 where tablea.postcode exists in tableb.postcode ?? 试着这样做: UPDATE tablea set pc

我有两张桌子:

表A的邮政编码列每行有一个邮政编码(示例行:E1 8NF)

表B中有一个邮政编码列,其中多个邮政编码由逗号分隔(示例行:E1 8NF、E1 8NG、E1 8NJ)

如果表A中的邮政编码存在于表B中,我想给它一个1

如何在postgresql中实现这一点?我的问题到目前为止

UPDATE tablea
set pcd = 1 where tablea.postcode exists in tableb.postcode ??
试着这样做:

UPDATE tablea set pcd = 1 where postcode in (select b.postcode from tableb);
试着这样做:

UPDATE tablea set pcd = 1 where postcode in (select b.postcode from tableb);

将列表存储在逗号分隔的字段中是一个非常糟糕的主意。在Postgres这样的数据库中,情况甚至更糟,因为它有非常合理的替代方案——比如数组和JSON字段。但是,有时我们会被其他人的糟糕决定所困扰

一种方法是:

update tablea a
    set pcd = 1
    where exists (select 1
                  from tableb b
                  where ',' || a.postcode || ',' like ',' || replace(b.postcodes, ', ', ',') || ','
                 );

将列表存储在逗号分隔的字段中是一个非常糟糕的主意。在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 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;