原创

MySQL根据父级id(pid)递归查找子集、MySQL自定义函数查看删除等(父子关系查找)


  最近在写文档系统,做删除的时候发现需要递归进行删除,以前没有注意这个事情,今天就详细研究一下,主要用到了MySQL的自定义函数(因为我用的5.7版本)。

定义函数

函数名 get_child_list

表名 zhe_document_relation

主键 id 父级 pid

推荐

  1. create function get_child_list(in_id varchar(10)) returns varchar(1000)
  2. READS SQL DATA
  3. begin
  4. declare ids varchar(1000) default '';
  5. declare tempids varchar(1000) DEFAULT '';
  6. set tempids = in_id;
  7. while tempids is not null do
  8. set ids = CONCAT_WS(',',ids,tempids);
  9. select GROUP_CONCAT(id) into tempids from zhe_document_relation where FIND_IN_SET(pid,tempids)>0;
  10. end while;
  11. return ids;
  12. end

不推荐

  1. delimiter $$
  2. drop function if exists get_child_list$$
  3. create function get_child_list(in_id varchar(10)) returns varchar(1000)
  4. begin
  5. declare ids varchar(1000) default '';
  6. declare tempids varchar(1000);
  7. set tempids = in_id;
  8. while tempids is not null do
  9. set ids = CONCAT_WS(',',ids,tempids);
  10. select GROUP_CONCAT(id) into tempids from zhe_document_relation where FIND_IN_SET(pid,tempids)>0;
  11. end while;
  12. return ids;
  13. end
  14. $$
  15. delimiter ;

递归查找

  1. select * from zhe_document_relation where FIND_IN_SET(id,get_child_list('1172'))

查看自定义函数

  1. // 查看自定义的所有函数
  2. show function status
  3. // 可以根据名称查看所有自定义的函数,支持模糊查询
  4. show function status like '名字';
  5. show function status like '%me';
  6. show function status like "ym_date"
  7. // 查看函数的创建语句
  8. show create function '函数名字';
  9. show create function ym_date
  10. //使用函数
  11. SELECT ym_date(established_date) from py_etl_private_fund_base_info_2_1

删除自定义函数

  1. // 删除对应函数
  2. drop function '函数名'
  3. drop function ym_date2;

鸣谢:

递归查找相关资料
https://www.cnblogs.com/guohu/p/14990788.html

自定义函数
https://blog.csdn.net/Lq_520/article/details/108128580

留言反馈
问题反馈渠道,如有软件无法下载或者其他问题可反馈。【由于某种原因,目前留言不展示】
用户需要登录后才能留言反馈