繁体   English   中英

检查 arrays 的交点

[英]Checking intersection of arrays

我的表如下所示:

ID top_id name_important 姓名 另一个列
111 [AAA,BBB] null
222 111 [AAA] X

我想检查的是top_idname_important不为空。 并且数组name_important中的值位于基于top_id的数组name中(那些 arrays 可能为空或可能不存在)。 在这种情况下, id 222 和 111 之间存在关系,因为id 222 在top_id列中有 111。 我想返回truefalse 你可以帮帮我吗?

我想使用 case when 子句,因为我还有其他情况要包括在内,如下所示:

with test as (
  select 111 as id, null as top_id, null as name_important, ["AAA", "BBB"] as name, null as another_column union all
  select 222, 111, ["AAA"], null, X
)

select id,
case when another_column is not null then true
when (question in the topic) then true
else false end result
from test

也许这样的东西可能适合:

with test as (
  select 111 as id, null as top_id, null as name_important, ["AAA", "BBB"] as name, null as another_column union all
  select 222, 111, ["AAA"], null, "X"
)
select 
  id,
  case 
    when another_column is not null then true
    when intersected then true
    else false
  end result
from (
  select test.*, ifnull(intersected, false) as intersected
  from test
  left join (
    select secondary.id, true as intersected
    from (
      select test.id, name
      from test, test.name as name
    ) as main
    join (
      select test.id, test.top_id, name_important
      from test, test.name_important as name_important
    ) as secondary
    on main.id = secondary.top_id and main.name = secondary.name_important
  ) using (id)
)

在此处输入图像描述

从您的示例中不清楚您是否需要数组中的所有值都匹配或任何值。 如果你想要任何价值,那么:

with test as (
  select 111 as id, null as top_id, null as name_important, ['AAA', 'BBB'] as name union all
  select 222, 111, ['AAA'], null
)
select t2.*, t1.name
from test t1 join
     test t2
     on t1.top_id = t2.id
where t1.name_important is not null and
      exists (select 1
              from unnest(t2.name) n1 join 
                   unnest(t1.name_important) n2
                   on n2 = n1
             )

如果都需要匹配:

with test as (
  select 111 as id, null as top_id, null as name_important, ['AAA', 'BBB'] as name union all
  select 222, 111, ['AAA'], null
)
select t1.*, t2.name
from test t1 join
     test t2
     on t1.top_id = t2.id
where t1.name_important is not null and
      not exists (select 1
                  from unnest(t1.name_important) n1 left join
                       unnest(t2.name) n2  
                       on n2 = n1
                  where n2 is null
                 );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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