> 데이터 베이스 > MySQL 튜토리얼 > 一个递归获取祖先元素值的MySQL函数范例

一个递归获取祖先元素值的MySQL函数范例

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
풀어 주다: 2016-06-07 17:07:54
원래의
1676명이 탐색했습니다.

test.sql:-- 创建测试数据 drop table if exists T1; CREATE TABLE T1 ( id bigint NOT NULL auto_increment, pid bigint,

test.sql:-- 创建测试数据
drop table if exists T1;
CREATE TABLE T1 (
id bigint NOT NULL auto_increment,
pid bigint,
code varchar(255),
PRIMARY KEY (id)
);
insert into t1(id,pid,code) values(1,null,'1');
insert into t1(id,pid,code) values(2,null,'2');
insert into t1(id,pid,code) values(3,1,'1.1');
insert into t1(id,pid,code) values(4,1,'1.2');
insert into t1(id,pid,code) values(5,2,'2.1');
insert into t1(id,pid,code) values(6,3,'1.1.1');
select * from t1 order by code;

-- 定义递归处理函数:获取祖先的id和code,并用符号'/'按序连接,id和code间用';'连接
DELIMITER $$
DROP FUNCTION IF EXISTS getAncestors $$
CREATE FUNCTION getAncestors(id bigint) RETURNS VARCHAR(1000)
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE r VARCHAR(1000);
DECLARE ri VARCHAR(1000);
DECLARE rc VARCHAR(1000);
DECLARE lev int;
DECLARE cid bigint;
DECLARE pid bigint;
DECLARE pcode VARCHAR(255);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

SET cid = id;
SET lev = 0;
SET ri = '';
SET rc = '';
REPEAT
SELECT p.id,p.code into pid,pcode FROM T1 c inner join T1 p on p.id=c.pid where c.id=cid;
IF NOT done THEN
SET cid = pid;
if length(ri) > 0 then
SET ri = concat(cast(pid as char),'/',ri);
SET rc = concat(cast(pid as char),'/',rc);
else
SET ri= cast(pid as char);
SET rc= pcode;
end if;
END IF;
UNTIL done END REPEAT;
if length(ri) > 0 then
SET r = concat(ri,';',rc);
else
SET r = null;
end if;
RETURN r;
END $$
DELIMITER ;
-- 返回:null;
select getAncestors(1);
-- 返回:'1;1';
select getAncestors(3);
-- 返回:'1/3;1/1.1';
select getAncestors(6);

linux

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿