如果 table 包含来自 table b 的另一列的子字符串,则使用 table b 的列值更新列 table

update column table with value of column from table b if it contains substring from another column from table b

有 2 个 table 如下:

Table a                        Table b

country_name                   id | string_bone   | country_name
------------------------       ---+---------------+---------------
usa                            1  | usa           | united states  
u s a                          2  | u s a         | united states
united states of america       3  | america       | united states
america                        4  | ...           | ...

如果 table_a.country_name 中包含 table_b.string_bone,我需要用 table_b.country_name 更新 table_a.country_name

我试过这个:

UPDATE table_a a
SET country_name = b.country_name
WHERE EXISTS (SELECT country_name
              FROM table_b
              WHERE a.country_name LIKE '%' || string_bone || '%') b;

我希望 table_a 更新后看起来像这样:

Table a                        

country_name                   
------------------------       
united states                            
united states                          
united states      
united states                        

Here dbfiddle link.

OK,这个需求很容易实现,如下图:

update table_a a set country_name = b.country_name from table_b b where a.country_name ~ b.country_name;

数据示例如下:

postgres=# select * from table_a;
       country_name       
--------------------------
 usa
 u s a
 united states of america
 america
(4 rows)

postgres=# select * from table_b;
 country_name 
--------------
 america
 usa
 u s a
(3 rows)

postgres=# update table_a a set country_name = b.country_name from table_b b where a.country_name ~ b.country_name;
UPDATE 4
postgres=# select * from table_a;
 country_name 
--------------
 usa
 u s a
 america
 america
(4 rows)

尝试以下操作:

UPDATE table_a a
    SET country_name = b.country_name
    from table_a t
    inner join table_b b
    on t.country_name LIKE '%' || b.string_bone || '%';