简体   繁体   中英

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

There are 2 table like below:

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  | ...           | ...

I need to update table_a.country_name with table_b.country_name if table_b.string_bone is contained in table_a.country_name .

I tried this:

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;

I would like table_a to look like this after the update:

Table a                        

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

Here the dbfiddle link.

OK, it's easy to implement this requirement, like below:

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

The data example as below:

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)

Try the following:

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 || '%';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM