当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL递归查询_函数语法检查_GROUP_CONCAT组合结果集的使用

MySQL递归查询_函数语法检查_GROUP_CONCAT组合结果集的使用

2018年10月17日  | 移动技术网IT编程  | 我要评论

1-前言:

在mysql使用递归查询是很不方便的,不像sqlserver可以直接使用声明变量,使用虚拟表等等。如:declare,begin ...  end   ,while ,if 等等。

在mysql可以通过创建函数,来使用上面的流程控制语句,mysql对函数的语法检查也是很苛刻的,可以说很烦人,不熟悉的人估计会哭。。。

 

2-递归查询关键部分:

  a-我的表结构:

  

 

  b-我的递归脚本:

  用于查询:当前类目id及所有的父级元素的id使用逗号分割开的一个字符串:

  下面脚本里使用了组合结果集的一个函数:group_concat,使用该函数可以在查不到结果的时候继续给pid赋值,从而跳出循环,详细可参考文章下面的注意点。

  select parentid into pid from product_leimu where 1=2; -- 找不到数据的情况下, into 无法给pid赋值,pid结果不变,

  select group_concat(parentid) into pid from product_leimu where 1=2; -- 找不到数据的情况下,通过函数group_concat组合之后,可以继续使用into 给pid赋值,pid结果为null

   

drop function if exists `fn_getleimupath`;

create definer = `sa`@`%` function `fn_getleimupath`(`subid` int)
 returns varchar(1000)
begin
declare pathid varchar(4000) default subid;
declare pid int default subid;

while pid>0 do
    select group_concat(parentid) into pid from product_leimu where id = pid;
    if pid>0 then
        set pathid = concat(pid, ',', pathid);
    end if;
end while;

return pathid;
end;

 

  查询结果展示:

  

 

3-一些需要注意的点,函数的一些特殊语法检查:

 a-脚本结束标记检查:  分号检查:

  如:每个独立的脚本语句;   流程控制语句结尾:end if;  end;   end while;

b-流程控制语句组合:   

  如: 

   if 条件 then 

    代码

  elseif

    代码

       end if;

 

  while 条件 do

    代码

  end while;

c-特殊函数的使用:

  函数:group_concat:将结果集链接在一起,使用逗号分隔,group_concat([distinct] 要连接的字段 [order by asc/desc 排序字段] [separator ‘分隔符’])

  备注: 这个函数可以在找不到数据的情况下,继续执行从而给into的变量赋值。   比较神奇:

select parentid into pid from product_leimu where 1=2;     -- 找不到数据的情况下, into 无法给pid的结果不变,
select group_concat(parentid) into pid from product_leimu where 1=2;   -- 找不到数据的情况下,通过函数group_concat组合之后,可以继续使用into 给pid赋值,null

  我们这里是想在查不到的结果的时候,通过while的判断结束循环,如果不通过group_concat函数将结果传给pid,那么将会进入无线循环当中,是很坑的!! 下面脚本的代码结果是:2

declare pid int;

select parentid into pid from product_leimu where 1=2;

if pid is null then
    set pid=1;
end if;

select group_concat(parentid) into pid from product_leimu where 1=2;

if pid is null then
    set pid=2;
end if;

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网