2017-03-09 53 views
0

我有2個表: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 ?? 

回答

2

你可以轉換的逗號分隔的列表到一個數組,然後使用,在一個子選擇:

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; 
0

試試這個方法:

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

以逗號分隔字段,其存儲列表是一個非常糟糕的主意。在像Postgres這樣的數據庫中,它有更加合理的選擇 - 例如數組和JSON字段。但是,有時候我們會堅持其他人的非常糟糕的決定。

的一種方法是:

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