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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With