[英]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'.我知道哪个标签被填充看起来是随机的,但这里有一些更多的细节:每个 id 都有一个相应的名称,但我只对某些类型的名称感兴趣——带有前缀“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.我希望能够扫描array_of_ids
,检查数组中的 id 是否与我感兴趣的str
匹配,并使用相应的名称填充新变量label
。 I hope this is clear!我希望这很清楚! Happy to edit if necessary!如有必要,很乐意编辑!
I realized that I wasn't making use of the PRESTO's array functions .我意识到我没有使用 PRESTO 的数组函数。 This solution is a little clunky since it requires you to look up each id/name pair outside of the solution, but it works.这个解决方案有点笨拙,因为它需要您在解决方案之外查找每个 id/name 对,但它有效。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.