标准 SQL 中的 BigQuery 连接数组
Posted
技术标签:
【中文标题】标准 SQL 中的 BigQuery 连接数组【英文标题】:BigQuery Join Array in standard SQL 【发布时间】:2016-08-10 08:42:14 【问题描述】:我正在使用标准 SQL,并且我有表 Order
:
"Order" table
我正在尝试将它与表 MenuItem
加入它
"MenuItem" table
在Order
item_ids 数组和MenuItem
__id__ 整数列上并获取MenuItem
价格数组,但我收到错误:
不支持引用其他表的相关子查询,除非它们可以去相关,例如通过将它们转换为有效的 JOIN。
如何避免这个错误?
查询:
WITH menu_items AS
(
SELECT
__id__,
price
FROM
`potykion.MenuItem`
)
SELECT
*,
ARRAY(
SELECT
price
FROM
UNNEST(item_ids) AS id
JOIN
menu_items
ON
id = menu_items.__id__
)
FROM
`potykion.Order`
【问题讨论】:
什么是item_details
?我在 Orders
表的示例数据中没有看到它。
我猜item_details
是其中一张表中的记录。不过,请提供您的表的架构,其中包含几行示例和预期结果。 - 一般而言 - 请编辑您的问题以显示您遇到问题的代码的Minimal, Complete, and Verifiable example,然后我们可以尝试帮助解决具体问题。你也可以阅读How to Ask。
预期输出是什么? - 仍然不清楚 - 是订单的字段加上订单中所有商品的总价吗?
我需要用价格数组替换 item_ids 数组
【参考方案1】:
试试下面(BigQuery 标准 SQL)
WITH Orders AS (
SELECT 1 AS id, ARRAY[1,2,3] AS item_ids UNION ALL
SELECT 2 AS id, ARRAY[4,5] AS item_ids UNION ALL
SELECT 3 AS id, ARRAY[1,4,6] AS item_ids
),
MenuItems AS (
SELECT 1 AS __id__, 1.1 AS price UNION ALL
SELECT 2 AS __id__, 1.2 AS price UNION ALL
SELECT 3 AS __id__, 1.3 AS price UNION ALL
SELECT 4 AS __id__, 1.4 AS price UNION ALL
SELECT 5 AS __id__, 1.5 AS price UNION ALL
SELECT 6 AS __id__, 1.6 AS price UNION ALL
SELECT 7 AS __id__, 1.7 AS price
)
SELECT
*,
ARRAY(
SELECT price
FROM UNNEST(item_ids) AS id
JOIN MenuItems
ON __id__ = id
) AS prices
FROM Orders
餐桌订单:
表格菜单项:
结果:
【讨论】:
好吧,我的数组创建表达式实际上是一样的,我想我得到了错误,因为 MenuItems 是另一个表。 希望我的“练习”能有所帮助!【参考方案2】:在数组创建表达式中加入连接的解决方案是正确的,但它不适用于单独的表。另一种解决方案是数组聚合:
WITH Orders AS (
SELECT 1 AS id, ARRAY[1,2,3] AS item_ids UNION ALL
SELECT 2 AS id, ARRAY[4,5] AS item_ids UNION ALL
SELECT 3 AS id, ARRAY[1,4,6] AS item_ids
),
MenuItems AS (
SELECT 1 AS __id__, 1.1 AS price UNION ALL
SELECT 2 AS __id__, 1.2 AS price UNION ALL
SELECT 3 AS __id__, 1.3 AS price UNION ALL
SELECT 4 AS __id__, 1.4 AS price UNION ALL
SELECT 5 AS __id__, 1.5 AS price UNION ALL
SELECT 6 AS __id__, 1.6 AS price UNION ALL
SELECT 7 AS __id__, 1.7 AS price
)
SELECT
id, ARRAY_AGG(price)
FROM Orders
JOIN MenuItems ON __id__ in UNNEST(item_ids)
GROUP BY id
【讨论】:
以上是关于标准 SQL 中的 BigQuery 连接数组的主要内容,如果未能解决你的问题,请参考以下文章
BigQuery:查找 ID 类型为 RECORD 的数组并使用 SQL 连接辅助表中的数据
在 CLI 上使用 bq 从 BigQuery 标准 SQL 连接表中打印出漂亮的值表?