-1

当一列中的数据包含来自另一表列的某些单词并在 Case When 中使用它们时,我需要返回 true。我该如何解决(但我不能使用联接或交叉联接,因为我需要左表中的所有数据)?

SQL

需要结果

4

2 回答 2

0

当一列中的数据包含另一表列中的某些单词时,我需要返回 true

我发现这通常最简单地将第二个表总结为正则表达式并使用它:

select m.*,
       (case when regexp_contains(m.name, d1.pattern) then 'organic'
             when regexp_contains(m.name, d2.pattern) then 'social'
        end) as source
from main_table m cross join
     (select string_agg(name, '|') as pattern
      from dictionary_1
     ) d1 cross join
     (select string_agg(name, '|') as pattern
      from dictionary_2
     ) d2;
于 2021-08-30T11:00:46.880 回答
0

在字典很长的情况下 - 正则表达式模式本身可能会变得昂贵,影响查询性能。尝试以下方法作为一种选择

select name,
  case 
    when (select logical_or(regexp_contains(t.name, name)) from dictionary_1) then 'organic'
    when (select logical_or(regexp_contains(t.name, name)) from dictionary_2) then 'social_media'
    else 'other'
  end source
from Main_table t
于 2021-08-30T19:21:17.213 回答