简体   繁体   中英

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 try trigger a/b delete but give error for recursive trigger.

thanks

You might want to look into FOREIGN KEY constraints and CASCADE rather than using triggers. https://dev.mysql.com/doc/refman/5.7/en/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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