最近在写文档系统,做删除的时候发现需要递归进行删除,以前没有注意这个事情,今天就详细研究一下,主要用到了MySQL的自定义函数(因为我用的5.7版本)。
定义函数
函数名 get_child_list
表名 zhe_document_relation
主键 id 父级 pid
推荐
create function get_child_list(in_id varchar(10)) returns varchar(1000)
READS SQL DATA
begin
declare ids varchar(1000) default '';
declare tempids varchar(1000) DEFAULT '';
set tempids = in_id;
while tempids is not null do
set ids = CONCAT_WS(',',ids,tempids);
select GROUP_CONCAT(id) into tempids from zhe_document_relation where FIND_IN_SET(pid,tempids)>0;
end while;
return ids;
end
不推荐
delimiter $$
drop function if exists get_child_list$$
create function get_child_list(in_id varchar(10)) returns varchar(1000)
begin
declare ids varchar(1000) default '';
declare tempids varchar(1000);
set tempids = in_id;
while tempids is not null do
set ids = CONCAT_WS(',',ids,tempids);
select GROUP_CONCAT(id) into tempids from zhe_document_relation where FIND_IN_SET(pid,tempids)>0;
end while;
return ids;
end
$$
delimiter ;
递归查找
select * from zhe_document_relation where FIND_IN_SET(id,get_child_list('1172'))
查看自定义函数
// 查看自定义的所有函数
show function status
// 可以根据名称查看所有自定义的函数,支持模糊查询
show function status like '名字';
show function status like '%me';
show function status like "ym_date"
// 查看函数的创建语句
show create function '函数名字';
show create function ym_date
//使用函数
SELECT ym_date(established_date) from py_etl_private_fund_base_info_2_1
删除自定义函数
// 删除对应函数
drop function '函数名';
drop function ym_date2;
鸣谢: