根据第三个表触发UPDATE以删除另一个表中的行

时间:2016-10-23 19:04:53

标签: postgresql triggers plpgsql sql-delete

我正在尝试为以下表创建触发器:

CREATE TABLE public.first (
 userid bigint,
 name varchar
);

 CREATE TABLE public.second (
 userid bigint,
 companyid bigint
);

CREATE TABLE public.visibility_matrix (
 name varchar,
 companyid bigint
);

每当表格first中的某一行更新时,触发器都应该使用userid并在表userid中搜索相同的second。如果存在,则从visibility_matrix中删除companyid中从第二个表中提取CREATE OR REPLACE FUNCTION pos_org_rel_refresh() RETURNS trigger AS $$ DECLARE r Integer ; BEGIN IF TG_OP='UPDATE' THEN DELETE FROM visibility_matrix where companyid=NEW.companyid; RETURN NEW; END IF; END; $$ LANGUAGE 'plpgsql'; 的行/。

以下是我的尝试:

触发功能:

CREATE TRIGGER test_trigger  
AFTER UPDATE 
ON first
FOR EACH ROW  
EXECUTE PROCEDURE pos_org_rel_refresh();

触发:

res.push({date: data21.date,description: data21.action});
console.log(JSON.stringify(res));
console.log(res.toString());

1 个答案:

答案 0 :(得分:1)

使用USING clause of DELETE加入另一个表:

触发功能:

CREATE OR REPLACE FUNCTION pos_org_rel_refresh()
  RETURNS trigger AS  
$func$
-- DECLARE
--    r int;  -- not used in function body
BEGIN  
-- IF TG_OP='UPDATE' THEN  -- redundant while func is only used in AFTER UPDATE trigger
   DELETE FROM public.visibility_matrix v
   USING  public.second s
   WHERE  s.userid = NEW.userid
   AND    v.companyid = s.companyid;
-- END IF;

RETURN NEW;  --  and don't place this inside the IF block either way

END
$func$  LANGUAGE plpgsql;  -- don't quote the language name

触发:

CREATE TRIGGER test_trigger  
AFTER UPDATE ON first
FOR EACH ROW EXECUTE PROCEDURE pos_org_rel_refresh();