我正在使用标准SQL,我有表Order
:
我试图加入表格MenuItem
在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`
答案 0 :(得分:3)
使用连接内部数组创建表达式的解决方案是正确的,但它不适用于单独的表。替代解决方案是阵列聚合:
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
答案 1 :(得分:2)
尝试以下(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