使用递归获取Bigquery SQL表中节点的所有子节点

问题描述 投票:0回答:2

我正在使用bigquery中的一个数据集,该数据集具有父子关系,但不指示final_parent...

我的数据看起来像这样:

| id   | parent  |
| -----| --------|
| AA   | AB      |
| AB   | AC      |
| ..   | ..      |

行要么是问题,要么是答案,所有答案都会汇总为一个问题,但是您可以回答一个答案,因此存在这种递归图形结构...我想要的是获得单个问题的所有答案,从与该问题的行 ID...

我生成了以下查询 - 我认为它对于该任务来说在逻辑上是正确的:

WITH RECURSIVE tbl_1 AS(
    (SELECT *
    FROM source_table 
    WHERE (id = xxxxxxxxxxx) OR (parent = xxxxxxxxxxx)) 
      UNION ALL
      (SELECT *
      FROM source_table 
      WHERE (parent IN (SELECT DISTINCT id FROM tbl_1) 
        AND (id NOT IN (SELECT DISTINCT id FROM tbl_1)))) 
   )

SELECT *
FROM tbl_1

但是我收到以下错误...

ERROR:
 400 A recursive reference from inside an expression subquery is not allowed at [9:49]

我认为这只是bigquery中尚未实现的东西?尽管如此,关于如何做到这一点有什么建议吗?非常感谢!!

sql recursion graph google-bigquery
2个回答
1
投票

尝试以下

with recursive tbl as (
  select *, 1 pos  from your_table 
  where question not in (select answer from your_table) 
  union all
  select t1.question, t2.answer, pos + 1
  from tbl t1 
  join your_table t2
  on t2.question = t1.answer
)
select question, string_agg(answer order by pos) answers
from tbl
group by question           

对于虚拟数据,如下例所示

enter image description here

输出是

enter image description here


0
投票

当您对同一问题有多个答案时该怎么办? @米哈伊尔

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.