【问题标题】:SQL Server - Contains QuerySQL Server - 包含查询
【发布时间】:2018-04-18 02:44:58
【问题描述】:

使用 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 和 #4 行。

我也可以试试这个:

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

这不会返回任何行。

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

所以基本上,我正在尝试执行以下操作,但使用包含查询:

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

谢谢!

【问题讨论】:

    标签: sql sql-server contains sql-like


    【解决方案1】:

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

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

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

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

    然后在该列上建立索引。

    【讨论】:

    • 对计算列的好调用,甚至没有想到。
    猜你喜欢
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多