代码之家  ›  专栏  ›  技术社区  ›  Russ P

SQL Server-包含查询

  •  3
  • Russ P  · 技术社区  · 7 年前

    使用SQL Server 2014和以下数据:

    ID          Address         City            State
    1           55 Main St      Dallas          TX
    2           4 Elm Blvd      Cupertino       CA
    3           66 Walnut       Miami           FL
    4           21 Main Ave     Cupertino       CA
    

    我试图跨多个列使用包含查询来查找匹配项,但无法找到正确的语法。在本例中,我有查询部分:

    CONTAINS ((Address, City, State), '"main" or "cupertino")
    

    返回行#1、#2和amp#4.

    我也可以试试这个:

    CONTAINS ((Address, City, State), '"main" and "cupertino")
    

    这不会返回任何行。

    不过,我想知道的是,如何使用包含查询,使用搜索词“main”和“cupertino”返回第4行。

    因此,基本上,我尝试使用contains查询执行以下操作:

    WHERE (Address LIKE '%main%' OR City LIKE '%main%' OR Zip LIKE '%main%') AND (Address LIKE '%cupertino%' OR City LIKE '%cupertino%' OR Zip LIKE '%cupertino%')
    

    1 回复  |  直到 7 年前
        1
  •  2
  •   Gordon Linoff    7 年前

    表达式用于 CONTAINS() 在每一列上独立计算(正如您可能已经猜到的)。一种解决方案是尝试:

    CONTAINS((Address, City, State), '"main"') AND
    CONTAINS((Address, City, State), '"cupertino"')
    

    更传统的方法是添加计算列并将其用于索引:

    alter table t add acs as (Address + ' ' + City + ' ' + State) persisted;
    

    然后在该列上建立索引。