如果列表包含表b另一列的子字符串,则用表b的列值更新列表

时间:2019-05-30 08:59:49

标签: sql database postgresql pattern-matching postgresql-9.5

有2个表格,如下所示:

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.country_name,我需要用table_b.string_bone更新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链接。

2 个答案:

答案 0 :(得分:1)

好的,很容易实现此要求,如下所示:

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)

答案 1 :(得分:1)

尝试以下操作:

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