【问题标题】:Join on a 2 Column Struct in BigQuery在 BigQuery 中加入 2 列结构
【发布时间】:2021-05-12 01:03:10
【问题描述】:

我想在大查询中使用结构将平面表连接到表上,但该表需要连接结构中的 2 列。有没有办法做到这一点?以下是示例数据和我尝试过的数据。

prices_table

| row | id1       | id2       | price  |
| --- | --------- | --------- | ------ |
| 1   | 0000001   | a         |  12000 |
| 2   | 0000001   | c         |  15000 |
| 3   | 0000002   | c         |   2000 |
| 4   | 0000004   | a         |   5000 |
array_table

| item    | array.id1 | array.id2 |
| ------- | --------- | --------- |
| apple   | 0000001   | a         |
|         | 0000002   | b         |
|         | 0000003   | c         |
| pear    | 0000004   | a         |
|         | 0000005   | b         |
|         | 0000006   | c         |

我在想我可以做这样的事情:

SELECT p.*, a.item
FROM prices_table p
LEFT JOIN array_table a
  ON id1 IN UNNEST(array.id1)
  AND id2 IN UNNEST(array.id2) 

但它会导致不正确的连接

expected

| row | id1       | id2       | price  | item  |
| --- | --------- | --------- | ------ | ----- |
| 1   | 0000001   | a         |  12000 | apple |
| 2   | 0000001   | c         |  15000 | null  |
| 3   | 0000002   | c         |   2000 | null  |
| 4   | 0000004   | a         |   5000 | pear  |
actual

| row | id1       | id2       | price  | item  |
| --- | --------- | --------- | ------ | ----- |
| 1   | 0000001   | a         |  12000 | apple |
| 2   | 0000001   | c         |  15000 | apple | < incorrect
| 3   | 0000002   | c         |   2000 | apple | < incorrect
| 4   | 0000004   | a         |   5000 | pear  |

【问题讨论】:

    标签: sql arrays struct google-bigquery


    【解决方案1】:

    您可以在取消嵌套后使用with offset 对齐数组:

    SELECT p.*, a.item
    FROM prices_table p LEFT JOIN
         (array_table a CROSS JOIN
          unnest(a.id1) i1 with offset as n1 JOIN
          unnest(a.id2) i2 with offset as n2
          ON n1 = n2
         )
         ON p.id1 = i1 AND p.id2 = i2;
    

    【讨论】:

      【解决方案2】:

      使用下面的方法

      select * from prices_table p
      left join (select item, id1, id2, from array_table a, a.array)
      using(id1, id2)
      

      如果应用于您问题中的样本数据 - 输出是

      【讨论】:

      • 你有机会尝试吗?
      猜你喜欢
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 2020-03-14
      • 2012-07-28
      • 2021-07-26
      • 1970-01-01
      相关资源
      最近更新 更多