Get the App
SLTechnology News&Howtos  ›  Database  › 

How does mysql query child nodes

Shulou Source: shulou.com Published: 2022-06-01 02:10:23 10月25日 Update

This article will explain in detail how mysql queries child nodes, Xiaobian thinks it is quite practical, so share it with you as a reference, I hope you can gain something after reading this article.

mysql query child node method: first create menu table, and insert data; then use the statement to query, the code is [select id from(select t1.id,if(find_in_set(parent_id, @ pies) > 0......)].

mysql query child node method:

Create menu table:

CREATE TABLE `menu`( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'menu id',`parent_id` int(11) DEFAULT NULL COMMENT ' parent nodeid',`menu_name` varchar(128) DEFAULT NULL COMMENT 'menu name',`menu_url` varchar(128) DEFAULT '' COMMENT ' menu path',`status` tinyint(3) DEFAULT '1' COMMENT 'menu status 1-valid; 0-null, PRIMARY KEY (`id`) ENGINE=InnoDB AUTO_INCREMENT=12212 DEFAULT CHARSET=utf8;

Insert data:

INSERT INTO `menu` VALUES ('0 ', null, ' menu0','','1');INSERT INTO `menu` VALUES ('1 ', ' 0','menu1','', ' 1');INSERT INTO `menu` VALUES ('11 ', ' 1','menu11','', ' 1');INSERT INTO `menu` VALUES ('12 ', ' 1','menu12','', ' 1');INSERT INTO `menu` VALUES ('13 ', ' 1','menu13','', ' 1');INSERT INTO `menu` VALUES ('111 ', ' 11','menu111','', ' 1');INSERT INTO `menu` VALUES ('121 ', ' 12','menu121','', ' 1');INSERT INTO `menu` VALUES ('122 ', ' 12','menu122','', ' 1');INSERT INTO `menu` VALUES ('1221 ', ' 122','menu1221','', ' 1');INSERT INTO `menu` VALUES ('1222 ', ' 122','menu1222','', ' 1');INSERT INTO `menu` VALUES ('12211 ', ' 122','menu12211','', ' 1');

The resulting directory structure is shown below:

query

Start with SQL statements:

select id from ( select t1.id, if(find_in_set(parent_id, @pids) > 0, @pids := concat(@pids, ',', id), 0) as ischild from ( select id,parent_id from re_menu t where t.status = 1 order by parent_id, id ) t1, (select @ pies:= id of menu node to query) t2 ) t3 where ischild != 0

For example, if you want to query all child nodes of menu node 12, the result of investigation is:

About mysql how to query child nodes to share here, I hope the above content can be of some help to everyone, you can learn more knowledge. If you think the article is good, you can share it so that more people can see it.

Tags: Menus nodes queries data methods more articles statements good practical valid code content name article status directory knowledge structure results Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Apple NVidia Shulou Technology MariaDB