2012-03-30 123 views
3

我試圖做一個觸發器,它會從一個基於表中選擇刪除另一個表中的行刪除基於多行選擇

operatorpositionsoperatorlinepos

positiontags 色譜柱line,position,tag

operatortags co lumns operatortag

我的觸發看起來像這樣

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; 

問題是可以有多個標籤爲一個位置,這樣子查詢將返回多行。我如何需要改變它,以便它可以使用多個標籤?

回答

3

如果我明白你想刪除所有標籤。
所以儘量用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; 
+0

工作,只是不得不將'新'改爲'舊' – 2012-03-30 12:05:11

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; 

改變從=IN運營商子查詢之前更換你=應於子返回多行

+0

是的,感覺愚蠢是如此容易:)還必須更改'新'爲'舊',因爲即時刪除 – 2012-03-30 11:48:42

3

更有效的方式來做到這一點是利用工作一個加入 -

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; 
+0

也可以,謝謝 – 2012-03-30 12:04:33