如何在MySQL中查找所有子行? [英] How to find all child rows in MySQL?
问题描述
我有一个层次结构系统设置程序,用于将项目的级别和父ID存储在数据库中.我要弄清楚的是如何找到用户选择的所有子行.这是表结构的示例:
I have a hierarchy system setup that stores the level and parent ID of the item in a database. What I am trying to figure out is how would I go about finding all the child rows of the one the user select. Here is a sample of the table structure:
+----+---------+----------+-------+
| Id | label | parentid | level |
+----+---------+----------+-------+
| 1 | honda | 0 | 1 |
| 2 | accord | 1 | 2 |
| 3 | civic | 1 | 2 |
| 4 | element | 1 | 2 |
| 5 | v4 | 2 | 3 |
| 6 | v6 | 2 | 3 |
+----+---------+----------+-------+
因此,如果有人删除honda
,我将如何删除层次结构中的所有内容?数据库只会降到3级.
So, if someone deletes honda
, how would I go about deleting everything down the hierarchy? The database will only ever have down to a level 3.
推荐答案
Refer, Recursive MySQL Query with relational innoDB
我昨天发布了同样的答案
I had posted a answer yesterday for the same
更新:
以下是基于上述链接的function
,但已根据您的DELETE
要求进行了量身定制
Below is a function
based on the above link, but has been tailored for your DELETE
requirements
CREATE PROCEDURE `delete_relations`(`_id` INT)
BEGIN
DECLARE delete_row_ids varchar(200);
DECLARE id, id2 varchar(200);
DECLARE rows_affected int;
SET delete_row_ids = _id;
SET id = _id;
SET id2 = id;
WHILE id2 IS NOT NULL DO
SET id = NULL;
SELECT GROUP_CONCAT( hierarchical_data.id ), CONCAT( GROUP_CONCAT( hierarchical_data.ID ),',',delete_row_ids) INTO id, delete_row_ids FROM hierarchical_data WHERE FIND_IN_SET( parentid , id2 ) GROUP BY parentid ;
SET id2 = id;
END WHILE;
DELETE FROM hierarchical_data where FIND_IN_SET(hierarchical_data.id, delete_row_ids);
SELECT row_count() INTO rows_affected;
if rows_affected > 0 THEN
SELECT delete_row_ids as row_ids_deleted;
ELSE
SELECT 'NO_ROWS_DELETED';
END IF;
END//
使用
CALL delete_relations(1)
删除id = 1 honda
希望它有帮助
这篇关于如何在MySQL中查找所有子行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!