数据量5k+,参照博客中给出的函数,运行一次需要15s,耗时太长,所以最终没有选择在Mysql中进行数据的遍历,而是采用在用户选取父节点时,在类中遍历,总体耗时会小很多,也不会给用户带来尺钝感。
平时使用Mysql 的函数不多,所以还是记录下来以后学习使用
- 在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 重启后即可生效
- 如果函数创建后修改运行会提示:
MySQL: create a function but it already exists
需要在函数提前添加DROP FUNCTION IF EXISTS funcName;
解决答案:stackflow - 函数体,这里我也是似懂非懂,直接贴地址: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