【问题标题】:repeated field in a subquery子查询中的重复字段
【发布时间】:2017-08-29 08:05:03
【问题描述】:

我正在尝试比较两个字符串列,其中一个在重复记录中并且位于子查询中:

#standardSQL
SELECT name AS produit
FROM   samples.overmind_reports 
WHERE  name IN (SELECT lines.article.sub_category.label FROM   samples.orders_lines)
ORDER BY produit 

错误:

无法访问具有类型值的字段文章 数组>,...>> [5:21]

表架构:

我试过FLATTEN,但它只是一个遗留功能?

#standardSQL
SELECT name AS produit
FROM   samples.overmind_reports 
WHERE  name IN (SELECT lines.article.sub_category.label FROM (FLATTEN(samples.orders_lines,lines)))
ORDER BY produit 

我明白了:

错误:语法错误:预期关键字 JOIN 但在 [6:50] 得到“)”

我没有使用UNNEST

【问题讨论】:

    标签: arrays subquery google-bigquery


    【解决方案1】:

    试试这个:

    #standardSQL
    SELECT
      t1.name AS produit
    FROM `samples.overmind_reports` t1
    WHERE EXISTS(SELECT 1 FROM `samples.orders_lines` t2, UNNEST(t2.lines) lines WHERE lines.article.sub_category.label = t1.name)
    ORDER BY 1
    

    您可以使用模拟数据进行测试:

    WITH `samples.overmind_reports` AS(
      SELECT 'name1' name UNION ALL
      SELECT 'name2' UNION ALL
      SELECT 'name3'
    ),
    `samples.orders_lines` AS(
      SELECT ARRAY<STRUCT<article STRUCT<sub_category STRUCT<label STRING> > > > [STRUCT(STRUCT(STRUCT('label' AS label) AS sub_category) AS article), STRUCT(STRUCT(STRUCT('name1' AS label) AS sub_category) AS article)] lines UNION ALL
      SELECT ARRAY<STRUCT<article STRUCT<sub_category STRUCT<label STRING> > > > [STRUCT(STRUCT(STRUCT('label' AS label) AS sub_category) AS article), STRUCT(STRUCT(STRUCT('name1' AS label) AS sub_category) AS article)] lines UNION ALL
      SELECT ARRAY<STRUCT<article STRUCT<sub_category STRUCT<label STRING> > > > [STRUCT(STRUCT(STRUCT('label' AS label) AS sub_category) AS article), STRUCT(STRUCT(STRUCT('name3' AS label) AS sub_category) AS article)] lines
    )
    
    SELECT
      t1.name AS produit
    FROM `samples.overmind_reports` t1
    WHERE EXISTS(SELECT 1 FROM `samples.orders_lines` t2, UNNEST(t2.lines) lines WHERE lines.article.sub_category.label = t1.name)
    ORDER BY 1
    

    【讨论】:

    • 非常感谢,当记录了 UNNEST 运算符时,在线文档并未涉及此交叉连接。
    • 成功了吗?至于交叉连接,请注意它只是一个正在实现的常规查询,但用作“子查询”。
    • 它适用于 WHERE 子查询或 WITH 子查询。它看起来像处理可变数组或嵌套表的 Oracle TABLE 运算符。
    • 酷:)。如果您认为答案对您有所帮助,请考虑接受/投票,因为这在 SO 中很重要:stackoverflow.com/help/someone-answers
    猜你喜欢
    • 2017-09-25
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    相关资源
    最近更新 更多