mysql 层级结构查询

时间:2024-05-01 15:55:04

描述:最近遇到了一个问题,在mysql中如何完成节点下的所有节点或节点上的所有父节点的查询? 在Oracle中我们知道有一个Hierarchical Queries可以通过CONNECT BY来查询,但是,在MySQL中还没有对应的函数!!! 下面给出一个function来完成的方法 下面是sql脚本,想要运行的直接赋值粘贴进数据库即可。

好记性不如烂笔头
下面给出一个function来完成的方法

下面是sql脚本,想要运行的直接赋值粘贴进数据库即可。

创建表treenodes(可以根据需要进行更改)


– Table structure for treenodes


DROP TABLE IF EXISTS treenodes;
CREATE TABLE treenodes (
id int(11) NOT NULL,
nodename varchar(20) DEFAULT NULL,
pid int(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


– Table structure for treenodes


插入几条数据


– Records of treenodes


INSERT INTO treenodes VALUES (‘’, ‘A’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘B’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘C’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘D’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘E’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘F’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘G’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘H’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘I’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘J’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘K’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘L’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘M’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘N’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘O’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘P’, ‘’);
INSERT INTO treenodes VALUES (‘’, ‘Q’, ‘’);

把下面的语句直接粘贴进命令行执行即可(注意修改传入的参数,默认rootId,表明默认treenodes)

根据传入id查询所有父节点的id

delimiter //
CREATE FUNCTION `getParList`(rootId INT)
RETURNS varchar()
BEGIN
DECLARE sTemp VARCHAR();
DECLARE sTempPar VARCHAR();
SET sTemp = '';
SET sTempPar =rootId; #循环递归
WHILE sTempPar is not null DO
#判断是否是第一个,不加的话第一个会为空
IF sTemp != '' THEN
SET sTemp = concat(sTemp,',',sTempPar);
ELSE
SET sTemp = sTempPar;
END IF;
SET sTemp = concat(sTemp,',',sTempPar);
SELECT group_concat(pid) INTO sTempPar FROM treenodes where pid<>id and FIND_IN_SET(id,sTempPar)>;
END WHILE; RETURN sTemp;
END
//
 

执行命令

select * from treenodes where FIND_IN_SET(id,getParList(15));
结果:

mysql 层级结构查询 
根据传入id查询所有子节点的id

delimiter //
CREATE FUNCTION `getChildList`(rootId INT)
RETURNS varchar() BEGIN
DECLARE sTemp VARCHAR();
DECLARE sTempChd VARCHAR(); SET sTemp = '$';
SET sTempChd =cast(rootId as CHAR); WHILE sTempChd is not null DO
SET sTemp = concat(sTemp,',',sTempChd);
SELECT group_concat(id) INTO sTempChd FROM treeNodes where FIND_IN_SET(pid,sTempChd)>;
END WHILE;
RETURN sTemp;
END
//

执行命令

select * from treenodes where FIND_IN_SET(id,getChildList(7));
结果:

mysql 层级结构查询