Standard SQL query to get the corresponding record field with another table (Google BigQuery)

I have two tables

1) table main

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

and I have another table that stores a bunch of Android phone identifiers like this

2) table android

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

Is there a way that I can get all the rows in the main table, where the row contains an entry with type android and id, which is also in android android.

+4
source share
1 answer

below should do it

#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

you can test it with dummy data

#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
+1
source

Source: https://habr.com/ru/post/1673156/


All Articles