3

I'm trying to make a trigger that will remove rows from one table based on select in another table

table operatorpositions columns operator, line, pos

table positiontags columns line, position, tag

table operatortags columns operator, tag

My trigger looks like this

CREATE TRIGGER removeOperatorPosition AFTER DELETE ON operatorpositions
    FOR EACH ROW
    BEGIN
        DELETE FROM operatortags WHERE gen = NEW.operator 
            AND tag = (SELECT tag FROM positiontags WHERE position = NEW.pos AND line = NEW.line);            
    END;

Problem is there can be multiple tags for one position, so subquery will return multiple rows. How do I need to change this so it will work with multiple tags?

0

3 Answers 3

3

If I understood you you want to delete all tags.
so try to replace your = before the subquery with IN

CREATE TRIGGER removeOperatorPosition AFTER DELETE ON operatorpositions
    FOR EACH ROW
    BEGIN
        DELETE FROM operatortags WHERE gen = NEW.operator 
            AND tag IN (SELECT tag FROM positiontags WHERE position = NEW.pos AND line = NEW.line);            
    END;
Sign up to request clarification or add additional context in comments.

Comments

3
CREATE TRIGGER removeoperatorposition AFTER DELETE
ON operatorpositions
FOR EACH ROW
BEGIN
  DELETE FROM operatortags
  WHERE  gen = new.operator
         AND tag IN (SELECT tag
                     FROM   positiontags
                     WHERE  position = new.pos
                            AND line = new.line);
END; 

Changing from = to IN operator should work on subqueries returning multiple rows

1 Comment

Yep, feel stupid it was so easy :) Also had to change new to old because im deleting
3

A more efficient way to do it is to use a join -

CREATE TRIGGER removeOperatorPosition AFTER DELETE ON operatorpositions
    FOR EACH ROW
    BEGIN
        DELETE ot
        FROM operatortags ot
        INNER JOIN positiontags pt
            ON ot.tag = pt.tag
        WHERE ot.gen = OLD.operator 
        AND pt.position = OLD.pos
        AND pt.line = OLD.line;            
    END;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.