问题
I have table like this
id | col1 | col2
I need write trigger so: after inserting or updating column col1
, I need insert (update) same value in column col2
This is my trigger function:
CREATE FUNCTION upd () RETURNS TRIGGER AS '
BEGIN
UPDATE mytable SET
col2 = col1;
RETURN NULL;
END;
'
LANGUAGE plpgsql;
and this is self trigger:
CREATE TRIGGER upd_trigger
AFTER INSERT OR UPDATE ON mytable
FOR EACH ROW
EXECUTE PROCEDURE upd()
This not works because happening cycloning at UPDATE
event, right?
What is right syntax for do this?
回答1:
@a_horse and @David have already pointed out the superior solution with a GIN index for your case.
But one more thing concerning the answer to your original question: since you only need the trigger after inserting or updating column col1
, you should be using the more specific event UPDATE OF ..., available since Postgres 9.0:
CREATE TRIGGER upd_trigger
BEFORE INSERT OR UPDATE OF col1 ON mytable
FOR EACH ROW
EXECUTE PROCEDURE upd()
This way you could even prevent endless loops / recursion ("cycloning" as you call it) in an AFTER
trigger. But it's still generally more sensible to use a BEFORE
trigger, like @a_horse already provided.
回答2:
You don't need an update, just assign the value:
CREATE FUNCTION upd () RETURNS TRIGGER AS
$body$
BEGIN
new.col2 := to_tsvector(new.col1);
RETURN new;
END;
$body$
LANGUAGE plpgsql;
And you need to do this in the before trigger:
CREATE TRIGGER upd_trigger
BEFORE INSERT OR UPDATE ON mytable
FOR EACH ROW
EXECUTE PROCEDURE upd()
Edit:
As @DavidAldridge has pointed out in his comment, it's probably easier to index the ts_vector() directly:
create index col1_vector
on mytable (to_tsvector(col1))
using gin;
A query using
where to_tsvector(col1) = '...'
would then be able to use that index.
回答3:
Well if the value for col2 is deterministically dependent only on that of col1 then col2 shouldn't be stored at all.
来源:https://stackoverflow.com/questions/16507123/cycloning-in-trigger