在Bigquery中编写递归查询的最简单方法

时间:2015-02-02 22:39:53

标签: sql google-bigquery

这是编写递归查询的最简单方法[如Connect By Prior]。 假设一个表有两个字段:ID和ParentId

表格数据如下:

ID  ParentId
======================= 
 1  2 
 2  3 
 3  4 
 4  5 
 5  6 
 6  null


Result should be 

Level1  Level2  Level3  Level4  Level5  Level6  Level7  Leevl8 ...  Level20 
   1     2      3       4       5       6

一种方法是:

SELECT ID AS Level1,
       PARENTID AS Level2,
       tab3.PARENTID AS Level3 ,
       tab4.PARENTID AS Level4,
       tab5.PARENTID AS Level5,
       tab6.PARENTID AS Level6 ,
       tab7.PARENTID AS Level7,
       tab8.PARENTID AS Level8,
       tab9.PARENTID AS Level9 ,
       tab10.PARENTID AS Level10,
       tab11.PARENTID AS Level11,
       tab12.PARENTID AS Level12 ,
       tab13.PARENTID AS Level13,
       tab14.PARENTID AS Level14,
       tab15.PARENTID AS Level15 ,
       tab16.PARENTID AS Level16,
       tab17.PARENTID AS Level17,
       tab18.PARENTID AS Level18 ,
       tab19.PARENTID AS Level19,
       tab20.PARENTID AS Level20
FROM
  (SELECT *
   FROM [poc.Extab] tab
   LEFT JOIN [poc.Extab] tab3 ON tab.PARENTID =tab3.ID
   LEFT JOIN [poc.Extab] tab4 ON tab3.PARENTID =tab4.ID
   LEFT JOIN [poc.Extab] tab5 ON tab4.PARENTID =tab5.ID
   LEFT JOIN [poc.Extab] tab6 ON tab5.PARENTID =tab6.ID
   LEFT JOIN [poc.Extab] tab7 ON tab6.PARENTID =tab7.ID
   LEFT JOIN [poc.Extab] tab8 ON tab7.PARENTID =tab8.ID
   LEFT JOIN [poc.Extab] tab9 ON tab8.PARENTID =tab9.ID
   LEFT JOIN [poc.Extab] tab10 ON tab9.PARENTID =tab10.ID
   LEFT JOIN [poc.Extab] tab11 ON tab10.PARENTID =tab11.ID
   LEFT JOIN [poc.Extab] tab12 ON tab11.PARENTID =tab12.ID
   LEFT JOIN [poc.Extab] tab13 ON tab12.PARENTID =tab13.ID
   LEFT JOIN [poc.Extab] tab14 ON tab13.PARENTID =tab14.ID
   LEFT JOIN [poc.Extab] tab15 ON tab14.PARENTID =tab15.ID
   LEFT JOIN [poc.Extab] tab16 ON tab15.PARENTID =tab16.ID
   LEFT JOIN [poc.Extab] tab17 ON tab16.PARENTID =tab17.ID
   LEFT JOIN [poc.Extab] tab18 ON tab17.PARENTID =tab18.ID
   LEFT JOIN [poc.Extab] tab19 ON tab18.PARENTID =tab19.ID
   LEFT JOIN [poc.Extab] tab20 ON tab19.PARENTID =tab20.ID)

1 个答案:

答案 0 :(得分:0)

BigQuery并没有真正让你在功能方面使用很多东西,所以我认为你唯一的解决方案是,正如你所写的那样,对于"充实"你的加入。

不幸的是,我认为这对于BigQuery来说可能是非常耗费资源的,并且您的查询可能会超时,所以要小心这一点