简体   繁体   English

MySQL的:删除行,其中列= ID后删除ID

[英]mysql : delete rows where column = ID after delete ID

I have 1 table like this 我有一张这样的桌子

ID   parent
1    null
2    1
3    1

now when I delete ID 1 I need auto delete all rows which parent = 1 . 现在,当我删除I​​D 1时,我需要自动删除parent = 1的所有行。 I try trigger a/b delete but give error for recursive trigger. 我尝试触发a / b删除,但递归触发时出错。

thanks 谢谢

You might want to look into FOREIGN KEY constraints and CASCADE rather than using triggers. 您可能想研究FOREIGN KEY约束和CASCADE,而不是使用触发器。 https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html https://dev.mysql.com/doc/refman/5.7/zh-CN/create-table-foreign-keys.html

Yes you cant use trigger for the same table which may result in dead lock so here you cant use trigger. 是的,您不能对同一表使用触发器,这可能导致死锁,因此在这里您不能使用触发器。
You should use foreign key. 您应该使用外键。 Here is an example 这是一个例子

ALTER TABLE `employee` ADD INDEX ( `parent_id` );


ALTER TABLE `employee` ADD CONSTRAINT `employee_ibfk_1` FOREIGN KEY ( `parent_id` ) REFERENCES `test`.`employee` (
`id`
) ON DELETE CASCADE ON UPDATE CASCADE ;

Here when you delete the parent data all the child rows will be deleted. 在这里,当您删除父数据时,所有子行都将被删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM