1

我正在尝试在 MySQL 上创建触发器,但我遇到了语法问题,我无法找到。如果有更多经验的人可以帮助我,那就太好了(这是我第一次使用 MySQL!)...

我创建此触发器的原因是为了删除所有与“service_descriptor”具有多对多关系的孤立“标签”(这两个实体由 service_labels 链接)。

我的代码是:

CREATE TRIGGER `trg_delete_orphan_label` AFTER DELETE 
FOR EACH ROW ON `restdb`.`service_labels`  
  DELETE FROM `restdb`.`labels`
   WHERE EXISTS (SELECT *
                   FROM old D 
              LEFT_JOIN `restdb`.`service_labels` SL ON SL.`id_label` = D.`id_label` 
                                                    AND D.`id_service` = SL.`id_service`
                  WHERE SL.`id_label` IS NULL
                        `restdb`.`labels`.`id` = D.SL.`id_label`); 

提前致谢 !

4

3 回答 3

1

你错过了 AND

试试这个代码

CREATE TRIGGER `trg_delete_orphan_label` AFTER DELETE FOR EACH ROW ON `restdb`.`service_labels`   
    DELETE 
    FROM 
        `restdb`.`labels` 
    WHERE 
        EXISTS (SELECT 
                    * 
                FROM 
                    old D LEFT_JOIN 
                    `restdb`.`service_labels` SL ON 
                        SL.`id_label` = D.`id_label` AND 
                        D.`id_service` = SL.`id_service` 
                WHERE 
                    SL.`id_label` IS NULL AND
                    `restdb`.`labels`.`id` = D.SL.`id_label`                         
                    );  
于 2010-06-17T14:22:07.033 回答
1

您的触发器存在一些问题,最明显的是“FOR EACH ROW”的位置,以及您将 OLD 视为表格的方式,而实际上它只是一行。

这应该适合你:

DROP TRIGGER IF EXISTS `trg_delete_orphan_label`;

CREATE TRIGGER `trg_delete_orphan_label` AFTER DELETE ON `service_labels` 
FOR EACH ROW
    DELETE FROM `labels`
    WHERE `id` = OLD.`id_label`
    AND NOT EXISTS (
        SELECT NULL
        FROM `service_labels` SL 
        WHERE SL.`id_label` = `labels`.`id`                        
    );                     
于 2010-06-17T16:09:43.850 回答
0

谢谢大家...由于您的帮助,我终于解决了...

最后的工作是:

trg_delete_orphan_label删除后创建触发器restdbservice_descriptor
对于每一行从 中删除restdblabels 不在的id地方(选择restdb…… 从service_labels…… ); id_labelrestdbservice_labels

于 2010-06-17T18:31:38.610 回答