I’m creating a trigger to update one table upon the insertion of a row in another table. In this update statement, I need to select a value from the first table. I need to then use this selected value in two places in the update statement. Here’s the trigger statement I have now:
CREATE TRIGGER rsrcInsTrig AFTER INSERT ON jos_resources
FOR EACH ROW
UPDATE newtbl
SET subtree_count = subtree_count + 1
WHERE lft <= (SELECT lft FROM newtbl WHERE taxon_id = NEW.taxon_id)
AND rgt >= (SELECT lft FROM newtbl WHERE taxon_id = NEW.taxon_id);
This works fine, but isn’t very elegant (I don’t need to be told that ‘newtbl’ isn’t a good name for a table; I didn’t make it). Clearly, I would like the subquery to be run only once, with the value saved and used twice. If this were a programming language, I would define a variable.
Is there a way to do what I want? Is it even really an issue (note that ‘newtbl’ has over 1.5 million entries, so queries on it are not insignificant)? The other questions on this topic were solved using joins, but I don’t believe that applies here.
1 Answer