Mysql 根据父节点查询所有子节点函数

数据量5k+,参照博客中给出的函数,运行一次需要15s,耗时太长,所以最终没有选择在Mysql中进行数据的遍历,而是采用在用户选取父节点时,在类中遍历,总体耗时会小很多,也不会给用户带来尺钝感。

平时使用Mysql 的函数不多,所以还是记录下来以后学习使用

  1. 在Mysql 中函数创建后会提示This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its de的错误信息,参照博客:MySQL 创建函数报错 This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators
    解决办法由两个:
    • 在函数体前写一句 set global log_bin_trust_function_creators=TRUE; 但是每次重启后都需要重新运行一遍
    • 在my.cnf配置文件中设置
      log-bin-trust-function-creators=1 重启后即可生效
  2. 如果函数创建后修改运行会提示:MySQL: create a function but it already exists
    需要在函数提前添加DROP FUNCTION IF EXISTS funcName;
    解决答案:stackflow
  3. 函数体,这里我也是似懂非懂,直接贴地址:Mysql递归获取某个父节点下面的所有子节点和子节点上的所有父节点
    其中IF(exp1,exp2,exp3)将会依次执行三个表达式,如果1不成功就执行2,同样不成功执行3
    FIND_IN_SET :是查询在改字符串中是否有指定的字符,
    在这里插入图片描述
create table mrm_level(
    id int auto_increment,
    name char(255) not null ,
    parentId int not null,
    contentId int not null ,
    path longtext ,
    type boolean,
    primary key (id)
)engine = InnoDB default charset = utf8;




drop function if exists getChildList;
delimiter  $$
create function getChildList(pid int) returns varchar(2000)
begin
    declare str varchar(100);
    declare cid varchar(100);
    set str = ' ';
    set cid = pid;
    while cid is not null do
        set str = concat(str,',',cid);
        select group_concat(contentId) into cid from mrm_level where find_in_set(parentId,cid)>0 ;
        end while;
    set str = substring(str,2);
    return str;
end$$;
    delimiter ;

select * from mrm_level where find_in_set(id,getChildList(2)) and type =0
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值