【问题标题】:Select query where in with partial match [duplicate]选择部分匹配的查询[重复]
【发布时间】:2019-01-29 16:49:55
【问题描述】:

我想从[Column] 中选择所有在其字符串中包含列表中单词的行,如下所示:

select [Column]
from [db]
where [Column] like '%some%' or 
      [Column] like '%word%' or
      [Column] like '%and%' or
      [Column] like '%another%' 

但是,由于我的单词列表很长,我不想重复or [Column] like '%%'。有没有更好的方法来写这个?我正在使用 SQL Server Management Studio。

【问题讨论】:

  • 您好,请提供您的清单和格式
  • or 可能是最好的方法,除非你有全文索引。

标签: sql arrays sql-server select


【解决方案1】:

使用临时表或变量表并将WHERE 移动到JOIN

DECLARE @PartialMatches TABLE (PartialMatch VARCHAR(100))

INSERT INTO @PartialMatches (PartialMatch)
VALUES ('some'),('word'),('and'),('another')

select 
    D.[Column]
from 
    [db] AS D 
    INNER JOIN @PartialMatches AS P ON D.[Column] LIKE '%' + P.PartialMatch + '%'

您可以选择在表格或外部添加类似的特殊字符 (%)。将它们放在桌面上会提供更大的灵活性,例如,您可以将 some%%word 放在桌面上。

【讨论】:

    【解决方案2】:

    这个(匹配列表或不匹配列表)对我有用...

    declare @matchs table ( match varchar(50));
    declare @notmatchs table ( notmatch varchar(50));
    insert into @matchs (match) values ('%matchfield1%');
    insert into @notmatchs (notmatch) values ('%nomatch1'), ('nomatch2%');
    
    select e.* 
    from mytable e
    where not exists (select top 1 1 from @notmatchs nm where e.ObjectName like nm.notmatch)
    and exists (select top 1 1 from @matchs m where e.ObjectName like m.match)
    

    【讨论】:

      【解决方案3】:

      您可以用以下格式编写查询。

      select [Column]
      from [db]
      where [Column] like '%[some-word-and-another]%'
      

      【讨论】:

      • 这不会提供与 OP 所期望的相同的输出。
      • 它不会提供所需的输出
      • 是的,这是不正确的,它只是给了我所有不为空或空白的东西
      • 是的,我必须检查我的答案,它会返回所有匹配条件文本的行
      猜你喜欢
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 2013-07-17
      • 2016-11-28
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多