【问题标题】:Select a string that is contained inside a string from a different table从不同的表中选择包含在字符串中的字符串
【发布时间】:2020-08-11 16:46:13
【问题描述】:

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

table1

id     fruit     updateablefield

table2

id     fruitbowl updateablefield

示例数据

table1

1 | apple

2 | orange

3 | mango

4 | grape

table2

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 列是使用逗号聚合的字符串。我也试过 where block in fruitbowls,但它不允许我以这种方式使用。 UNNEST 也是不允许的。如何在水果和水果碗之间做出平等声明

【问题讨论】:

  • 修复 table2,使其不在字符串中存储多个值。至少,将列更改为数组。但最好每行有一个值。
  • 添加触发器和触发器函数定义,也不清楚什么时候要通过这个触发器更新什么
  • @GordonLinoff 我不能这样做,因为 table2 是 table1 的聚合。如果我这样做,那么 table2 就会变成 table1,用户根本无法浏览数千行
  • @AkhileshMishra 添加了
  • 你在哪个事件上调用这个触发函数?插入/更新之前/之后?

标签: sql postgresql triggers


【解决方案1】:

试试这个:

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

【讨论】:

  • 谢谢老兄!意识到我必须在 (new.fruitbowls,', ') 之间加上一个空格,因为我已经用空格聚合了它们
猜你喜欢
  • 2018-03-01
  • 2013-11-15
  • 1970-01-01
  • 1970-01-01
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
  • 2012-11-21
  • 1970-01-01
相关资源
最近更新 更多