如果父母删除mysql,触发删除孩子
你好,伙计们,我对此代码有iSues,我使用mysql workbench
我有2个表格:
表1:孩子
`id` , // primary key
`id_parent`,
`name`
表2:
`id`, // primary key
`name`
我可以在其中使用1个父行,以及child> child.id_parent =
parent.id
我如何编程当我删除父行并删除其所有子行时触发的触发器child.id_parent
= parent.id
我一直在尝试此操作,但是当我尝试删除父行时,
DELIMITER $$
CREATE TRIGGER parent_deleted
before DELETE
ON parent FOR EACH ROW
BEGIN
delete from child where `child.id_parent`=`parent.id`;
END$$
DELIMITER ;
我却尝试更改parent.id for old.parent_id,并在删除触发器之后尝试过,因为我遇到了这个错误,似乎没有任何工作:
DELETE FROM `prueba_luisdi`.`parent`
WHERE (`id` = '9')
1054:未知列'prueba_luisdi.parent.id in in where子句'
必须是触发器
hello fellows im having isues with this code, im using mysql workbench
I have this schema with 2 tables:
table 1: child
`id` , // primary key
`id_parent`,
`name`
table 2: parent
`id`, // primary key
`name`
where I can use 1 parent row for many child rows, and child.id_parent
=parent.id
how can i program a trigger that fires when i delete a parent row and deletes all of his child rows where child.id_parent
=parent.id
I've been trying this but not succesfully when I try to delete a parent row
DELIMITER $
CREATE TRIGGER parent_deleted
before DELETE
ON parent FOR EACH ROW
BEGIN
delete from child where `child.id_parent`=`parent.id`;
END$
DELIMITER ;
I tried changing the parent.id for old.parent_id, and tried after delete trigger too, nothing seems to work since i get this error:
DELETE FROM `prueba_luisdi`.`parent`
WHERE (`id` = '9')
1054: Unknown column 'prueba_luisdi.parent.id' in 'where clause'
it has to be a trigger because if I use foreign key delete on cascade, then I cant register the child deleted on my log_changes table
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我同意以上关于使用级联外键的评论。但是,如果您不使用外国钥匙(很多人不使用)或不使用支持外国钥匙的存储引擎,则这不是一个选择。
如果要引用
id
要删除在触发器中的行的列,请使用old.id
。https://dev.mysql.com/doc/doc/refman/ 8.0/en/trigger-syntax.html 说:
看起来像这样:
还要注意,如果您使用反式攻击来界定合格的标识符,则每个部分都是单独的标识符。
I agree with the comment above about using a cascading foreign key. But if you don't use foreign keys (many people do not) or don't use a storage engine that supports foreign keys, this isn't an option.
If you want to reference the
id
column of the row being deleted in a trigger, useOLD.id
.https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html says:
This would look like this:
Also notice that if you use back-ticks to delimit qualified identifiers, each part is a separate identifier.