Mysql method of querying child nodes: first create the 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, @pids) > ; 0...)】.
More related free learning recommendations:mysql tutorial(Video)
Mysql method of querying child nodes:
Create menu table:
CREATE TABLE `menu` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '菜单id', `parent_id` int(11) DEFAULT NULL COMMENT '父节点id', `menu_name` varchar(128) DEFAULT NULL COMMENT '菜单名称', `menu_url` varchar(128) DEFAULT '' COMMENT '菜单路径', `status` tinyint(3) DEFAULT '1' COMMENT '菜单状态 1-有效;0-无效', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=12212 DEFAULT CHARSET=utf8;
Insert data:
INSERT INTO `menu` VALUES ('0', null, '菜单0', ' ', '1'); INSERT INTO `menu` VALUES ('1', '0', '菜单1', '', '1'); INSERT INTO `menu` VALUES ('11', '1', '菜单11', '', '1'); INSERT INTO `menu` VALUES ('12', '1', '菜单12', '', '1'); INSERT INTO `menu` VALUES ('13', '1', '菜单13', '', '1'); INSERT INTO `menu` VALUES ('111', '11', '菜单111', '', '1'); INSERT INTO `menu` VALUES ('121', '12', '菜单121', '', '1'); INSERT INTO `menu` VALUES ('122', '12', '菜单122', '', '1'); INSERT INTO `menu` VALUES ('1221', '122', '菜单1221', '', '1'); INSERT INTO `menu` VALUES ('1222', '122', '菜单1222', '', '1'); INSERT INTO `menu` VALUES ('12211', '1222', '菜单12211', '', '1');
The resulting directory structure is as shown below:
Query Issue the sql statement:
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 @pids := 要查询的菜单节点 id) t2 ) t3 where ischild != 0
For example, if you want to query all the child nodes of menu node 12, the result of the investigation is:
The above is the detailed content of How to query child nodes in mysql. For more information, please follow other related articles on the PHP Chinese website!