sql:喜欢任何 vs 喜欢所有

sql: like any vs like all

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

出于某种原因,第一个 LIKE 与 ANY 一起工作得很好 - 它 returns 所有包含狗粮、血统或有益的记录。

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

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

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 行都是正确的。

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
;