子查询中的重复字段

时间:2017-08-29 08:05:04

标签: arrays subquery google-bigquery

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

#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 

错误:

  

无法访问类型值的字段文章   ARRAY>,...>>在[5:21]

表架构:

enter image description here

我尝试使用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

1 个答案:

答案 0 :(得分:0)

试试这个:

#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