Recursive query

旧城冷巷雨未停 提交于 2020-01-24 12:37:13

问题


I have a table which contains the following fields

  • Supervisorid
  • Empid

This is just like a referral program. A guy can refer 3 guys under him i.e, 3 is referring three guys namely 4 5 8 similarly 4 is referring 9 10 and 11 likewise 8 is referring 12, 13 it goes like this..

I want a query to get all EmpId under Supervisor 3


回答1:


Do you want us to write the solution for you, or explain a bit how recursive queries can be built up ?

An example of how they are built up is on http://publib.boulder.ibm.com/infocenter/db2luw/v8//topic/com.ibm.db2.udb.doc/ad/samples/clp/s-flt-db2.htm.

The IBM DB2 redbook has an entire chapter on SQL recursion.

The gist is that the following steps are generally involved:

  • you define a "seed". SELECT SUPID, EMPID, 1 AS LVL FROM EMP WHERE SUPID = 3;

  • you assign to this a name. WITH SRC AS <your seed here>

  • you define the way to go to the 'next level', starting from the seed, using the assigned name. SELECT SRC.SUPID, F.EMPID, SRC.LVL+1 FROM SRC, EMP WHERE SRC.EMPID=EMP.SUPID

  • you combine the two together (inside the WITH clause) WITH SRC AS <your seed here> UNION ALL <the other SELECT here>

  • (optionally) you define which columns to select. SELECT EMPID, LVL FROM SRC.



来源:https://stackoverflow.com/questions/3995393/recursive-query

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