标准sql查询以获取与另一个表匹配的记录字段(Google BigQuery)

时间:2017-03-24 18:28:58

标签: sql google-bigquery

我有两张桌子

1)表main

   id    phone.type  phone.id
==============================
|   1   | android | adkfjagp |
|       | android | asdfasdf |
|       | iphone  | akfj2341 |
|       | iphone  | ada93519 |
------------------------------

我还有另一张表存储了一堆像这样的Android手机ID

2)表android

==============
|  adkfjagp  |
|   ...      |
--------------

有没有办法可以获取表格main中的所有行,其中行包含一个类型为android且id也在表android中的记录。

1 个答案:

答案 0 :(得分:1)

下面的

应该是

  
#standardSQL
SELECT m.*
FROM main AS m
CROSS JOIN (SELECT ARRAY_AGG(id) AS ids  FROM android) AS a
WHERE  (
  SELECT COUNT(1) 
  FROM UNNEST(phone) AS phone 
  WHERE phone.type = 'android' 
  AND phone.id IN UNNEST(a.ids)
) > 0

您可以使用以下虚拟数据进行测试

#standardSQL
WITH main AS (
  SELECT 
    1 AS id, 
    [STRUCT<type STRING, id STRING>
      ('android', 'adkfjagp'),
      ('android', 'asdfasdf'),
      ('iphone', 'akfj2341'),
      ('iphone', 'ada93519')
     ] AS phone UNION ALL
  SELECT 
    2 AS id, 
    [STRUCT<type STRING, id STRING>
      ('android', 'adkfjagp1'),
      ('android', 'bbbbbbbb1'),
      ('android', 'akfj2341'),
      ('iphone', 'ada93519')
     ] AS phone
),
android AS (
  SELECT 'adkfjagp' AS id UNION ALL
  SELECT 'bbbbbbbb' 
)
SELECT m.*
FROM main AS m
CROSS JOIN (SELECT ARRAY_AGG(id) AS ids  FROM android) AS a
WHERE  (
  SELECT COUNT(1) 
  FROM UNNEST(phone) AS phone 
  WHERE phone.type = 'android' 
  AND phone.id IN UNNEST(a.ids)
) > 0