• MySql 递归查询


    MySql 递归查询

    一、递归语句

    -- 向下递归函数
    SELECT GROUP_CONCAT('''', pk_dept , '''')  FROM rz.dept WHERE FIND_IN_SET(fr_pk_dept,'1070')>0;

    结果:

    设置某个部门下的所有子部门为无效:

    update rz.dept set zt ='0' WHERE FIND_IN_SET(fr_pk_dept,'部门ID')>0;

    二、自定义递归函数

    利用find_in_set()函数和group_concat()函数实现递归查询:

    1,向下递归:

    DROP FUNCTION IF EXISTS queryChildrenAreaInfo;
    CREATE FUNCTION queryChildrenAreaInfo(areaId INT) -- 或者 areaId char
    RETURNS VARCHAR(4000)
    BEGIN
    DECLARE sTemp VARCHAR(4000);
    DECLARE sTempChd VARCHAR(4000);
    
    SET sTemp='$';
    SET sTempChd = CAST(areaId AS CHAR);
    
    WHILE sTempChd IS NOT NULL DO
    SET sTemp= CONCAT(sTemp,',',sTempChd);
    SELECT GROUP_CONCAT(id) INTO sTempChd FROM t_areainfo WHERE FIND_IN_SET(parentId,sTempChd)>0;
    END WHILE;
    RETURN sTemp;
    END;

    调用方式:

    SELECT * FROM t_areainfo WHERE FIND_IN_SET(id,queryChildrenAreaInfo(4));

    2,向上递归:

    DROP FUNCTION IF EXISTS queryChildrenAreaInfo1;
    CREATE FUNCTION queryChildrenAreaInfo1(areaId INT)
    RETURNS VARCHAR(4000)
    BEGIN
    DECLARE sTemp VARCHAR(4000);
    DECLARE sTempChd VARCHAR(4000);
    
    SET sTemp='$';
    SET sTempChd = CAST(areaId AS CHAR);
    SET sTemp = CONCAT(sTemp,',',sTempChd);
    
    SELECT parentId INTO sTempChd FROM t_areainfo WHERE id = sTempChd;
    WHILE sTempChd <> 0 DO
    SET sTemp = CONCAT(sTemp,',',sTempChd);
    SELECT parentId INTO sTempChd FROM t_areainfo WHERE id = sTempChd;
    END WHILE;
    RETURN sTemp;
    END;

    调用方式:

    SELECT * from t_areainfo where FIND_IN_SET(id,queryChildrenAreaInfo1(7));
  • 相关阅读:
    linux驱动程序设计的硬件基础,王明学learn
    linux设备驱动概述,王明学learn
    应用程序调试工具gdb,王明学learn
    usb设备驱动描述,王明学learn
    OK6410移植madplay播放器,王明学learn
    bootstrap使用入门(bootstrap4.2.1版本)
    IntelliJ Idea 常用快捷键列表
    javaFX 多窗口编程
    Spring Boot框架入门教程(快速学习版)
    BindingNavigator 控件
  • 原文地址:https://www.cnblogs.com/lizm166/p/10319277.html
Copyright © 2020-2023  润新知