• postgresql 函数&存储过程 ; 递归查询


    函数:http://my.oschina.net/Kenyon/blog/108303

    紧接上述,补充一下:

    输入/输出参数的函数demo(输入作为变量影响sql结果,输出作为结果返回)

    create or replace function f_dept_salary_out2(int, out o_dept text,out o_salary text) 
    returns setof record as
    $$
    declare
        v_rec record;
    begin
        for v_rec in EXECUTE 'select departmentid as dept_id, sum(salary) as total_salary from f_get_employee() group by departmentid having departmentid='||$1 loop
            o_dept:=v_rec.dept_id;
            o_salary:=v_rec.total_salary;  
            return next;
        end loop; 
    end;
    $$
    language plpgsql;
    
    select * from f_dept_salary_out2(2);
    

      

     递归查询:http://my.oschina.net/kenshiro/blog/160129

    由于资源页的数据源没有,因此在这里重新做了个demo,如下:

    1. 准备数据

    create table Tag(
    id int,
    name text,
    parent_id int
    );
    
    insert into Tag values(1,'all products',-1),(2,'plastic',1),(3,'metal',1),(4,'toy',2),(5,'furniture',2),(6,'knife',3);
    

    这是一个产品的tag表。如下:

    树形描述如下:

    all products --------plastic--------toy

                         |                   |--furniture

                         |---metal --------knife

    2. 找子孙

    即:根据某个节点寻找子树。

    例如:找到plastic及下面所有的tag,sql如下:

    with recursive r as(
    select * from Tag where id = 2
    union all
    select Tag.* from Tag, r where Tag.parent_id = r.id
    )
    
    select * from r order by id;
    

    输出会如下:

    id  name      parent_id

    2   plastic       1

    4   toy            2

    4   furniture    2

    3. 找祖先

    即:根据某个节点寻找其所有父系节点。

    例如:找到knife的所有父辈们,sql如下:

    with recursive r as ( 
           select * from Tag where id = 6
         union   all
           select Tag.* from Tag, r where Tag.id = r.parent_id 
         ) 
    select * from r order by id desc;
    

    输出会如下:

    id          name             parent_id

    6           knife              3

    3           metal             1

    1           all products     -1

    后记:把r理解成下"当前"记录就好了。

  • 相关阅读:
    (原创) mac 10.9.2 eclipse 的 CDT 的 异常的修复
    (转) Virtual function
    (转) ROS NAMING AND NAMESPACES
    (转) Data structures
    (转) Dynamic memory
    java string类
    eclipse 的快捷键
    java抽象类和接口
    面向对象的三大特征
    Java 中的多态
  • 原文地址:https://www.cnblogs.com/Tommy-Yu/p/4192897.html
Copyright © 2020-2023  润新知