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

我有两张桌子

1)表主

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

我有另一个表存储这样的一堆Android手机ID

2)表android

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

有没有办法我可以获取表main中的所有行,其中行包含类型为android和id的记录,也在表android中.

最佳答案 下面应该成功

  

#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
点赞