FreeText Query is slow - includes TOP and Order By

前端 未结 6 1350
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-13 15:03

The Product table has 700K records in it. The query:

SELECT TOP 1 ID, Name FROM Product WHERE contains(Name, \'\"White Dress\"\') ORDER BY DateMadeN

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 15:53

    I have better solution.

    I. Let's first overview proposed solutions as they also may be used in some cases:

    1. OPTION (HASH JOIN) - is not good as you may get error "Query processor could not produce a query plan because of the hints defined in this query. Resubmit the query without specifying any hints and without using SET FORCEPLAN."

    2. SELECT TOP 1 * FROM (ORIGINAL_SELECT) ORDER BY ... - is not good, when you need to use paginating results from you ORIGINAL_SELECT

    3. sp_create_plan_guide - is not good, as to use plan_guide you have to save plan for specific sql statement, this won't work for dynamic sql statements (e.g. generated by ORM)

    II. My Solution contains of two parts 1. Self join table used for Full Text search 2. Use MS SQL HASH Join Hints MSDN Join Hints

    Your SQL :

    SELECT TOP 1 ID, Name FROM Product WHERE contains(Name, '"White Dress"') 
    ORDER BY DateMadeNew desc
    

    Should be rewritten as :

    SELECT TOP 1 p.ID, p.Name FROM Product p INNER HASH JOIN Product fts ON fts.ID = p.ID
    WHERE contains(fts.Name, '"White Dress"') 
    ORDER BY p.DateMadeNew desc
    

    If you are using NHibernate with/without Castle Active Records, I've replied in post how to write interceptor to modify your query to replace INNER JOIN by INNER HASH JOIN

提交回复
热议问题