根据select删除多行

时间:2012-03-30 11:35:50

标签: mysql subquery

我正在尝试创建一个触发器,它将根据另一个表中的select

从一个表中删除行

表格operatorpositionsoperatorlinepos

表格positiontagslinepositiontag

表格operatortagsoperatortag

我的触发器看起来像这样

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 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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运算符应该可以处理返回多行的子查询

答案 2 :(得分: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;