简体   繁体   English

运行嵌套的 CTE

[英]Running nested CTEs

On the BigQuery SELECT syntax page it gives the following:在 BigQuery SELECT语法页面上,它提供了以下内容:

query_statement:
    query_expr

query_expr:
    [ WITH cte[, ...] ]
    { select | ( query_expr ) | set_operation }
    [ ORDER BY expression [{ ASC | DESC }] [, ...] ]
    [ LIMIT count [ OFFSET skip_rows ] ]

I understand how the (second line) select could be either:我了解(第二行) select如何:

{ select | set_operation }

But what is the ( query_expr ) in the middle for?但是中间的( query_expr )是什么? For example, if it can refer to itself, wouldn't it make the possibility to construct a lisp-like query such as:例如,如果它可以引用自身,它是否有可能构造一个类似 lisp 的查询,例如:

with x as (select 1 a)
  (with y as (select 2 b) 
    (with z as (select 3 c)
      select * from x, y, z))

Actually, I just tested it and the answer is yes.实际上,我刚刚测试了它,答案是肯定的。 If so, what would be an actual use case of the above construction where you can use ( query_expr ) ?如果是这样,您可以使用( query_expr )的上述结构的实际用例是什么?

And, is there ever a case where using a nested CTE can do something that multiple CTEs cannot?并且,是否有使用嵌套 CTE 可以做多个 CTE 不能做的事情的情况? (For example, the current answer is just a verbose way or writing what would more properly be written with a single WITH expression with multiple CTEs) (例如,当前的答案只是一种冗长的方式,或者WITH具有多个 CTE 的单个WITH表达式编写更合适的内容)

This query might be useful in that case where a CTE is being referred to by subsequent CTEs.在 CTE 被后续 CTE 引用的情况下,此查询可能很有用。

For instance, you can use this if you want to join two tables, use expressions and query the resulting table.例如,如果您想连接两个表,使用表达式并查询结果表,您可以使用它。

with x as (select '2' as id, 'sample' as name )
(with y as ( select '2' as number, 'customer' as type)
(with z as ( select CONCAT('C00',id), name, type from x inner join y on x.id=y.number)
Select * from z))

The above query gives the following output :上面的查询给出了以下输出:

在此处输入图片说明

Though there are other ways to achieve the same, the above method would be much easier for debugging.虽然还有其他方法可以实现相同的效果,但上述方法会更容易调试。 Following article can be referred for further information on the use cases.可以参考以下文章以获取有关用例的更多信息。

The following construction might be useful to model how an ETL flow might work and to encapsulate certain 'steps' that you don't want the outer query to have access to.以下构造可能有助于对 ETL 流的工作方式进行建模并封装您不希望外部查询访问的某些“步骤”。 But this is quite a stretch...但这有点牵强……

WITH output AS (

  WITH step_csv_query AS (
         SELECT * FROM 'Sales.CSV'),
       step_filter_csv AS (
         SELECT * FROM step_csv_query WHERE Country='US'),
       step_mysql_query AS (
          SELECT * FROM MySQL1 LEFT OUTER JOIN MySQL2...),
       step_join_queries  AS (
          SELECT * FROM step_filter_csv INNER JOIN step_mysql_query USING (id)
  ) SELECT * FROM step_join_queries -- output is last step

) SELECT * FROM output -- or whatever we want to do with the output...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM