【问题标题】:sql: like any vs like allsql:喜欢任何与喜欢所有
【发布时间】:2017-03-21 10:25:16
【问题描述】:

我不明白为什么有时 LIKE 需要 ANY 而有时需要 ALL,这让我发疯了。我觉得我应该能够在这两种情况下使用 ANY (我正在尝试选择括号中任何正则表达式之后的记录)。

由于某种原因,第一个 LIKE 与 ANY 一起工作得很好 - 它返回所有带有 dog chow、谱系或有益的记录。

然而,第二个 LIKE 需要 ALL。否则,它不会遗漏带有零食、用品或湿的记录。但为什么?我觉得 ANY 是合适的形式。

where dsc_item like any ('%DOG CHOW%','%PEDIGREE%','%BENEFUL%')
and dsc_comm not like all ('%TREATS%','%SUPPLIES%', '%WET%')

【问题讨论】:

    标签: sql teradata


    【解决方案1】:

    LIKE ANY 转换为 ORed 条件,但 LIKE ALL 转换为 AND

    where
     (    dsc_item like '%DOG CHOW%'
       OR dsc_item like '%PEDIGREE%','%BENEFUL%'
     )
    and
     (     dsc_comm not like '%TREATS%' 
       AND dsc_comm not like '%SUPPLIES%'
       AND dsc_comm not like '%WET%'
     )
    

    如果您将AND 替换为OR,就像col <> 1 OR col <> 2 对于每个非NULL 行都是如此。

    【讨论】:

      【解决方案2】:
      like any        similar to      = any  
      like all        similar to      = all  
      not like any    similar to      <> any  
      not like all    similar to      <> all  
      

      select      'My name is Inigo Montoya, you killed mhy father, prepare to die!'  as str
      
                 ,case when str like any ('%Inigo%','%Donald%' ,'%Hillary%')      then 1 else 0 end -- 1
                 ,case when str like any ('%Adam%' ,'%Donald%' ,'%Hillary%')      then 1 else 0 end -- 0
                 ,case when str like all ('%Inigo%','%Montoya%','%father%')       then 1 else 0 end -- 1
                 ,case when str like all ('%Inigo%','%Montoya%','%mother%')       then 1 else 0 end -- 0
      
                 ,case when str not like any ('%Inigo%','%Montoya%','%mother%')   then 1 else 0 end -- 1
                 ,case when str not like any ('%Inigo%','%Montoya%','%father%')   then 1 else 0 end -- 0
                 ,case when str not like all ('%Adam%' ,'%Donald%' ,'%Hillary%')  then 1 else 0 end -- 1
                 ,case when str not like all ('%Inigo%','%Donald%' ,'%Hillary%')  then 1 else 0 end -- 0
      ;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-27
        • 2022-08-03
        相关资源
        最近更新 更多