简体   繁体   中英

The best way to delete items in hierarchy way from a DB table in mysql?

I have a database table of categories. Two of its columns are 'category_id' and 'parent_category' which i am using for deletion . The values of these columns are aligned as :

在此处输入图片说明

eg if i am deleting 'category_id' 10 then all its children(to any depth) 11,12,13 should also be deleted. please suggest me the best mysql query.

thanks in advance.

The easiest way seems to be this:

  1. Create a foreign key constraint between the parent_category and category_id column;
  2. Set cascade delete on.

     create table yourTable ( ... add constraint foreign key (parent_category) references yourTable(category_id) on delete cascade ) 

This will solve your problem totally without effort.

If you do not want to use foreign keys, so you can add a column parent_path

ALTER TABLE `table`
ADD `parent_path` varchar(255) NOT NULL DEFAULT ''
AFTER `parent_category`, COMMENT='';

Now create a procedure that creates the parent_path

DELIMITER $$
DROP PROCEDURE IF EXISTS UpdateParentPath$$

CREATE PROCEDURE UpdateParentPath()
    BEGIN
        DECLARE count INT;
        SET count = 1;

        WHILE count > 0 DO
            UPDATE `table` as `t`
                LEFT JOIN `table` as `p` ON `t`.`parent_category` = `p`.`category_id`
            SET `t`.`parent_path` = CONCAT(`p`.`parent_path`, IF(`p`.`parent_path` = '', '', ','), `p`.`category_id`);

            SELECT ROW_COUNT() INTO count;
        END WHILE;
    END$$
DELIMITER ;

Call this procedure

CALL UpdateParentPath();

And now ... finally ... you start deleting

DELETE FROM `table` WHERE `parent_category` = '9' OR `parent_path` LIKE '%,9,%'

Before every deleting or after insert/update is necessary call UpdateParentPath procedure.

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