从另一个表中选择一个包含在字符串内的字符串

问题描述

我需要根据table1上一列的字符串是否在table2上的另一列内进行更新

表1

id     fruit     updateablefield

表2

id     fruitbowl updateablefield

示例数据

表1

1 | apple

2 | orange

3 | mango

4 | grape

表2

1 | mango,pear,banana | false

2 |  grape,orange     | true

我的简化的更新触发器查询设置如下

CREATE OR REPLACE FUNCTION build.onholdview_update()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$

BEGIN               
if new.updateablefield = true then  update table1 set updateablefield = true 
   where '%' || a.fruit || '%' like new.fruitbowls;                                                                                      
end if;

 RETURN NEW;                                                                    
END;
        

$function$
; 

但是,这不起作用。如您所见,fruitbowls列是使用逗号对字符串进行汇总的。我还尝试了在果盘中的位置阻止,但不允许我以这种方式使用。也不允许使用UNnesT。如何在水果和水果盆之间做出平等的声明

解决方法

尝试一下:

CREATE OR REPLACE FUNCTION onholdview_update()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$

BEGIN               
if new.updateablefield = true then  
 update table1 set updateablefield = true 
   where fruit = any(regexp_split_to_array(new.fruitbowls,',')) ;                                                                                      
end if;

 RETURN NEW;                                                                    
END;
        

$function$
; 

DEMO