SQL Server: how to optimize “like” queries?

后端 未结 2 1367
我在风中等你
我在风中等你 2020-12-11 19:59

I have a query that searches for clients using \"like\" with wildcard. For example:

SELECT TOP (10) 
       [t0].[CLIENTNUMBER], 
       [t0].[FIRSTNAME], 
          


        
相关标签:
2条回答
  • 2020-12-11 20:42

    To do much for a LIKE where the pattern has the form '%XXX%', you want to look up SQL Server's full-text indexing capability, and use CONTAINS instead of LIKE. As-is, you're doing a full table scan, because a normal index won't help with a search for an item that starts with a wild card -- but a full-text index will.

    /* ... */
     WHERE (LTRIM(RTRIM([t0].[DOCREVNO])) = '0') 
       AND (contains([t0].[FIRSTNAME], 'John')) 
       AND (contains([t0].[LASTNAME], 'Smith')) 
       AND (contains([t0].[SSN], '123'))
       AND (contains([t0].[CLIENTNUMBER],'123')) 
       AND (contains([t0].[MDOCNUMBER], '123')) 
       AND ([t0].[CLIENTINDICATOR] = 'ON')
    
    0 讨论(0)
  • 2020-12-11 20:42

    Looks like some databases (PostgreSQL 7.1+, MySQL v3.23.23+, Microsoft-SQL v???, ) already contains such things:

    MySQL>> ALTER TABLE articles ADD FULLTEXT(body, title); MySQL>> SELECT * FROM articles WHERE MATCH(title, body) AGAINST ('PHP') MS-SQL>> SELECT ProductName FROM Products WHERE FREETEXT (ProductName, 'spread' ) PgSQL>> CREATE FUNCTION fti() RETURNS opaque AS '/path/to/fti.so' LANGUAGE 'C'; PgSQL>> CREATE TABLE articles_fti (string type, id oid); .... Oracle..., Sybase...

    0 讨论(0)
提交回复
热议问题