kgarthai
kgarthai

Reputation: 100

Using the result of a subquery twice in MySQL

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.

Upvotes: 2

Views: 2734

Answers (2)

Eugen Rieck
Eugen Rieck

Reputation: 65314

CREATE TRIGGER rsrcInsTrig AFTER INSERT ON jos_resources
FOR EACH ROW BEGIN
    DECLARE tmplft INT DEFAULT 0; -- assuming it really is an INT
    SELECT lft FROM newtbl WHERE taxon_id = NEW.taxon_id INTO tmplft;
    UPDATE newtbl
    SET subtree_count = subtree_count + 1
    WHERE lft <= tmplft
    AND rgt >= tmplft;
END

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1270713

You can express the WHERE clause a bit differently:

UPDATE newtbl
SET subtree_count = subtree_count + 1
WHERE (SELECT lft FROM newtbl WHERE taxon_id = NEW.taxon_id) between lft and rgt

Upvotes: 0

Related Questions