可以使用 BigQuery 中的 ARRAY_AGG 函数和 UNNEST 函数来实现嵌套表的合并。
假设有如下两张表:
Table1:
id | name | |
---|---|---|
1 | John | john@example.com |
2 | Jane | jane@example.com |
3 | Tom | tom@example.com |
Table2:
id | interests |
---|---|
1 | ["swimming", "running"] |
2 | ["hiking", "painting", "reading"] |
3 | ["football", "basketball", "coding", "reading"] |
其中 Table2 中 interests 字段是一个嵌套的数组。
要将两张表按照 id 合并,并将 interests 数组合并到 Table1 中,可以使用以下 SQL 语句:
SELECT
t1.id,
t1.name,
t1.email,
ARRAY_AGG(interests) AS interests
FROM
Table1 AS t1
LEFT JOIN
UNNEST(Table2.interests) AS interests
ON
t1.id = Table2.id
GROUP BY
t1.id,
t1.name,
t1.email
执行以上 SQL 语句后,会得到合并后的结果:
id | name | interests | |
---|---|---|---|
1 | John | john@example.com | ["swimming", "running"] |
2 | Jane | jane@example.com | ["hiking", "painting", "reading"] |
3 | Tom | tom@example.com | ["football", "basketball", "coding", "reading"] |
其中 interests 字段已经合并到了 Table1 中。