Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

standard sql query to get matching 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 which stores a bunch of android phone ids like this

2) table android

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

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

like image 357
Isa Avatar asked Oct 30 '22 10:10

Isa


1 Answers

below should make 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 below 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
like image 150
Mikhail Berlyant Avatar answered Nov 15 '22 06:11

Mikhail Berlyant