'Join on Id in Variant (Array) Snowflake
I have two tables t1 and t2 created as follows:
Create Tables
CREATE TABLE t1(
id integer AUTOINCREMENT START 1 INCREMENT 1,
name varchar(10) DEFAULT RANDSTR(10, random()),
id_array variant,
)
CREATE TABLE t2(
id integer AUTOINCREMENT START 1 INCREMENT 1,
name varchar(10) DEFAULT RANDSTR(10, random())
)
Goal
I am looking to join t2 to t1 if the id of the record exists in the t1 variant array.
What I've Tried
I came across the ARRAY_CONTAINS function which looked perfect. But with the following I am receiving no results:
SELECT t1.id, t2.name
FROM t1, t2
WHERE ARRAY_CONTAINS(t1.id_array, array_construct(t2.id))
How Do I Get This?
Any suggestions on how to achieve the following result?
t1 record:
{id: 1, name: 'A-123', ids_array: '["1", "2"]'}
t2 records:
{id: 1, name: 'test'},
{id: 2, name: 'test2'}
Desired Result
{id: 1, name: 'A-123', joined_name: 'test'},
{id: 1, name: 'A-123', joined_name: 'test2'}
Solution 1:[1]
ARRAY_CONTAINS expects the following parameters: variant and array:
SELECT t1.id, t2.name
FROM t1, t2
WHERE ARRAY_CONTAINS(t1.id_array, array_construct(t2.id))
should be rather:
SELECT t1.id, t2.name
FROM t1
JOIN t2
ON ARRAY_CONTAINS(t2.id::variant, t1.id_array)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lukasz Szozda |
