Hierarchical Query Needs to Pull Children, Parents and Siblings

被刻印的时光 ゝ 提交于 2020-01-13 02:47:08

问题


Can now pull the data, but am wondering if there is a better way to optimize the query for large data sets.

http://sqlfiddle.com/#!4/0ef0c/5

So basically I want to be able to supply the query a given org id and have it recursively pull its parents, its children, its siblings and its aunts and uncles. And then pull any Activities that are associated with that org hierarchy.

Org1 is the top level org, but it may or may not have a null parent.

Basically I was doing an up and down query to pull the children and the parent, but can only seem to get the siblings by adding another query. Finally got to another query with the help of a friend, but its very low on large data sets (4-5k of Activities).

Any insight would be greatly appreciated.


回答1:


If your org. structure is strictly hierarchical, then you might use this approach: http://www.ibase.ru/devinfo/DBMSTrees/sqltrees.html

The drawback is that you have to update the index on every update of the org structure. However org structures are usually read much more often then modified. So IMHO this should do the trick.




回答2:


The key to doing this is in the word "recursively". To do that, create a procedure that calls itself. This is an example for parents, but because it's using a cursor to scroll through entries, it should be straightforward for how to use this to find children and other relationships involving recursion.

CREATE OR REPLACE PROCEDURE find_parents( 
  org_id NUMBER, 
  lvl NUMBER DEFAULT 1) AS 

  c_parent table1.id%TYPE;
  c_name table1.name%TYPE;
  CURSOR c_parents (c_id table1.id%TYPE) IS
    SELECT parent, name FROM table1 WHERE (id = c_id);

  BEGIN
    dbms_output.put('-');
    OPEN c_parents(org_id);
    LOOP
      FETCH c_parents INTO c_parent, c_name;
      EXIT WHEN c_parents%notfound;
      dbms_output.put_line('Level ' || lvl || ' parent: [ID: ' || c_parent || ', NAME: ' || c_name || ']');
      find_parents(c_parent, lvl + 1);
    END LOOP;
    CLOSE c_parents;
  END;


来源:https://stackoverflow.com/questions/13655400/hierarchical-query-needs-to-pull-children-parents-and-siblings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!