简体   繁体   中英

Match an array of foreign keys in one table with primary key in another table?

I have a two tables. One like this:

id   | array_of_ids
----------------------
 001 | {012, 345, 789}
 002 | {789, 123, 456}
 003 | {234, 789, 567}
 004 | {543, 210, 789}

Another like this:

 ids  | str
-------------
 012 | am_name1
 345 | name2
 789 | name3
 123 | am_name4
 456 | name5
 234 | name6
 567 | am_name7
 543 | am_name8
 210 | name9

I want to create a table that looks like this:

id   | array_of_ids    | label
-----------------------------
 001 | {012, 345, 789} | name1
 002 | {789, 123, 456} | name4
 003 | {234, 789, 567} | name7
 004 | {543, 210, 789} | name8

I know that which label gets populated looks random, but here's some more details: every id has a corresponding name, but i am only interested in certain type of name -- the one's with the prefix 'am'. I want to be able to scan the array_of_ids , check if a id in the array matches a str i am interested in and the populate a new variable label with the correspond name. I hope this is clear! Happy to edit if necessary!

unnest() and join :

select t1.id, t1.array_of_ids,
       max(case when regexp_like(t2.name, '^am_') then substr(t2.name, 4) end)
from table1 t1 cross join
     unnest(t1.array_of_ids) t1_id(id) join
     table2 t2
     on t2.id = t1_id.id
group by t1.id, t1.array_of_ids;

I realized that I wasn't making use of the PRESTO's array functions . This solution is a little clunky since it requires you to look up each id/name pair outside of the solution, but it works.

SELECT id, array_of_ids,
  CASE WHEN CONTAINS(array_of_ids, 012) = TRUE THEN 'name1'
       WHEN CONTAINS(array_of_ids, 123) = TRUE THEN 'name4'
       WHEN CONTAINS(array_of_ids, 567) = TRUE THEN 'name7'
       WHEN CONTAINS(array_of_ids, 543) = TRUE THEN 'name8'
       ELSE NULL END AS label
FROM table1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM