我试图在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`);
提前致谢!
答案 0 :(得分:1)
你错过了
试试此代码
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`
);
答案 1 :(得分: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`
);
答案 2 :(得分:0)
谢谢大家......由于你的帮助,我最终解决了这个问题......
最后的工作是:
trg_delete_orphan_label
restdb
之后创建触发器service_descriptor
。restdb
对于每一行
从labels
删除。id
restdb
不在哪里(
选择service_labels
。id_label
。restdb
来自service_labels
。{{1}});